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 sandyreturn t[name]
=> gives nilreturn 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
The
ipairsiterator selects only the array elements with integer keys. To iterate over all keys you requirepairs, like this: