Question

I have this code written in Lua, it's just an example code, because the actual one I'm using is bigger than this, but this is the part I'm having problems.

Does anyone know why when I try to print what's inside the table t I get nil as result?

t = {
{name="John",sex="M",age=19},
{name="Susan",sex="F",age=20}
} 

for _ in ipairs(t) do 

    print("NAME: " .. t.name) 
    print("SEX: " .. t.sex) 
    print("AGE: " .. t.age)
    print("\n") 

end 

I mean, this is the result I get when I run the code:

attempt to concatenate field 'name' (a nil value)
Was it helpful?

Solution

Iterating over t doesn't change t. You need to specify where to put the values you are iterating over, and use those variables.

local t = {
    {name="John",sex="M",age=19},
    {name="Susan",sex="F",age=20}
} 

for index, value in ipairs(t) do 
    print("NAME: " .. value.name) 
    print("SEX: " .. value.sex) 
    print("AGE: " .. value.age)
    print("\n") 
end 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top