I'm a beginner in Lua.
I thought pushing values to a table using string keys would automatically also do number indexing but I think I was wrong about this.
My Code :
local t = {}
t.name = "John"
t.age = 30
print("Name : " .. t.name .. "\nAge : " .. t.age)
While this code works fine and prints the expected result,
Name : John
Age : 30
If I try to print the result this way,
print("Name : " .. t[1] .. "\nAge : " .. t[2])
I get the following error:
lua: main.lua:5: attempt to concatenate a nil value (field '?')
stack traceback:
main.lua:5: in main chunk
[C]: in ?
Does this mean I cannot iterate through the table using for
with number indexing without having to know the key strings?
If so, is there any work around to make the both way work?
local t = { ["name"] = "John", ["age"] = 30 }
as you can see the keys[1]
and[2]
are not present. It is also not possible to add number indexing because if the keys in a table aren't numbers, the order is unspecified. You don't need number indices to iterate a table withfor
. Just tryfor k,v in pairs(t) do print(k,v) end
. – Henri Menke