Reputation: 55
I have the following lua table :
t = {name="sandy", age="22", major="computerScience"}
I want to iterate over it, both methods below do NOT work
Method 1
function printAssociateTable(t) print("before the loop") for i,v in ipairs(t) do print(v) end end
Method 2
function printAssociateTable2(t) print("before the loop") for k in ipairs(t) do print("before the loop") print(k.. " is " ..t.k) end end
when I call either methods, they print "before the loop". so the problem the program is not entering the loop !
i tried to manually access the table, if i do this :
return t.name => gives sandy
return t[name] => gives nil
return t["name"] => gives sandy !
how can i iterate over my table ? kindly note that both methods work well with a simple array like this
a={"a","b","c","d"}
but i want it to work on my associative array
Upvotes: 1
Views: 2402
Reputation: 126752
The ipairs
iterator selects only the array elements with integer keys. To iterate over all keys you require pairs
, like this:
function printAssociateTable(t)
print("before the loop")
for i,v in pairs(t) do
print(v)
end
end
Upvotes: 7