Lua:表赋值中函数执行的顺序

我有一个 Lua 表和一个像这样的索引函数:

curIndex = 0

function index()
   curIndex = curIndex + 1
   return curIndex
end

t = {
  one = index(),
  two = index(),
  three = index(),
}

我知道遍历表对可能在任何顺序下给我键值 "one", "two", "three",尽管有经验和直觉的反对,这足以产生足够的不确定性,让我想要问这个问题:

保证函数 index() 在预期的解析顺序 (one, two, three) 中被执行,这样我可以始终依赖 t.one 有索引值 1,t.two == 2t.three == 3 吗?

原文链接 https://stackoverflow.com/questions/9335985

点赞
stackoverflow用户7625
stackoverflow用户7625

Table constructor 中的字段是按顺序计算的。这确保了通过索引和键添加的项目是按顺序添加的。你的表构造器:

t = {
  one = index(),
  two = index(),
  three = index(),
}

等同于:

do
    local temp = {}
    temp["one"] = index()
    temp["two"] = index()
    temp["three"] = index()
    t = temp
end
2012-02-17 22:09:53