【问题标题】:Lua Can anyone explain what this does?Lua 谁能解释一下这是做什么的?
【发布时间】:2016-02-02 07:17:24
【问题描述】:

我正在学习lua,谁能解释一下这段代码是如何工作的?

table = {1, 2, 3, 4, 5}

function num(table, start)
  table = start

  return function()
    i = i + 1
    if table[i - 1] then
      return i - 1,[table - 1]
    else
      return nil
  end
end

for k,v in ipairs(table) do
  print(k,v)
end

【问题讨论】:

  • return i - 1,[table - 1] 是语法错误。你在哪里看到这个脚本?
  • 它也缺少end for else 声明
  • 代码看起来很糟糕。 num 没有在其中任何地方使用;立即分配给它的table 参数,使其毫无意义; i 是一个全局变量,没有在任何地方定义,所以 i = i+1 会失败;正如 hjpotter 和 lukas 指出的那样,它的结构不正确。
  • 此代码将为您提供1,1 2,23,34,45,5 的输出。 num 函数永远不会被调用。如果它会 - 它会产生错误:没有足够的end 语句。或更早 - [t-1] 不是来自 Lua 的东西。好吧,它只是神秘的块 =)
  • 看起来 num 将成为一个迭代器。我的猜测是这不是所有的代码

标签: lua


【解决方案1】:

看起来该代码导致了自定义迭代器函数。但它还没有完成,这是我对它应该是什么样子的最佳猜测

tab = {1, 2, 3, 4, 5}

function num(tab, start)
  local i = start or 1
  return function()
    i = i + 1
    if tab[i - 1] then
      return i - 1,tab[i - 1]
    else
      return nil
    end
  end
end

for k,v in ipairs(tab) do
  print(k,v)
end

for k,v in num(tab) do
  print(k,v)
end

这段代码首先会遍历 tab 并打印键值对。接下来,它使用它制作的迭代器打印它之前的键值对。

迭代器继续返回,直到它返回 nil。然后for循环结束。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-15
    • 2015-08-12
    • 2015-07-08
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多