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

时间:2012-02-17 21:54:13

标签: parsing lua

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

curIndex = 0

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

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

我知道迭代表对可以给我任何顺序的键“一”,“二”,“三”。这创造了足够的不确定性,尽管经验和直觉相反,我想问这个问题:

是否保证函数index()在预期的解析序列(一,二,三)中执行,这样我就可以依赖索引值为t.one的{​​{1}} t.two == 2t.three == 3一直都在吗?

1 个答案:

答案 0 :(得分:2)

Table constructor字段按顺序进行评估。这可以保证按索引与键添加的项目按顺序添加。你的表构造函数:

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

相当于:

do
    local temp = {}
    temp["one"] = index()
    temp["two"] = index()
    temp["three"] = index()
    t = temp
end