Neekoy
Neekoy

Reputation: 2533

Lua - iterating through nested list

I'm going to simplify the situation as much as I can. I have the following code:

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 }
}

If I do the following, I get the correct output:

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

HOWEVER, if I iterate through the list, I get "nil" values for "l.x" and "l.properties.active":

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

Is there a different way I need to iterate through the variables in the lists, so I can get the values?

Upvotes: 0

Views: 288

Answers (1)

roeland
roeland

Reputation: 5741

That is not a nested table, but just a table containing strings. And, as you just saw, a string doesn't contain a value for the key "x".

You have to put the tables in a sequence:

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

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

local windows = {window1, window2}

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

Or, if you want to keep the list of strings and iterate over the strings, put the windows in a second table using these strings as a key.

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

Upvotes: 3

Related Questions