我有一个Lua表和一个像这样的索引函数:
curIndex = 0
function index()
curIndex = curIndex + 1
return curIndex
end
t = {
one = index(),
two = index(),
three = index(),
}
我知道迭代表对可以给我任何顺序的键“一”,“二”,“三”。这创造了足够的不确定性,尽管经验和直觉相反,我想问这个问题:
是否保证函数index()
在预期的解析序列(一,二,三)中执行,这样我就可以依赖索引值为t.one
的{{1}} t.two == 2
,t.three == 3
一直都在吗?
答案 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