Lua - 遍历嵌套列表

时间:2015-12-31 00:26:10

标签: lua

我会尽可能地简化这种情况。我有以下代码:

windows = { "window1", "window2" }

window1 = {
x = 100
y = 100
properties = { active = false, width = 200, height = 200 }
}

window2 = {
x = 0
y = 0
properties = { active = false, width = 200, height = 200 }
}

如果我执行以下操作,我会得到正确的输出:

print (window1.x)
OUTPUT: 0
print (window1.properties.active)
OUTPUT: false

但是,如果我遍历列表,我会得到" nil" " l.x"的值和" l.properties.active":

for _,l in ipairs(windows) do
    print (l)
    print (l.x)
    print (l.properties.active)
end

我是否需要以不同的方式遍历列表中的变量,以便获取值?

1 个答案:

答案 0 :(得分:3)

这不是嵌套表,而只是包含字符串的表。而且,如您所见,字符串不包含键"x"的值。

您必须按顺序放置

local window1 = {...} -- first table

local window2 = {...} -- second table

local windows = {window1, window2}

for _,l in ipairs(windows) do
    -- do stuff with l
end

或者,如果你想保留字符串列表并迭代字符串,请将这些字符串作为键放在第二个表中。

local windowNames = { "window1", "window2" }
local windows = {}

windows.window1 = {...} -- first table

windows.window2 = {...} -- second table

for _,l in ipairs(windowNames) do
    local ourWindow = windows[l]
    -- do stuff with ourWindow
end