1

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

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.