I have the following table defined which consists of tables defined under a string index as such:
local myTable = {
["str-1"] = {
id = 1,
value = "val"
},
["str-2"] = {
id = 2,
value = "val",
},
["str-3"] = {
id = 3,
value = "val",
}
}
for i, table in ipairs(myTable) do
print(i)
print(table)
end
I'm attempting to loop through the contents of the table however the print()
statements are not giving an output? I have placed a print statement to print both the current index of the loop and the table at that position.
This is because you are attempting to use an ipairs()
loop over an associative array.
Instead, you can use a pairs()
loop which supports iteration where the index of a table is associative:
for i, table in pairs(myTable) do
print(i)
print(table)
end
A pairs()
loop uses a key-value pair and works with associative tables, this also results in iteration not being conducted in order whereas an ipairs()
uses an index-value pair, the likes of which can be used on a regular table defined with numerical indexes.