tags:

views:

210

answers:

2

I have a table in lua with some data.

sometable = { 
    {name = "bob", something = "foo"},
    {name = "greg", something = "bar"}
}

I then want to loop through the table and assign a number to each name as a variable. New to lua and tried it like this.

for i,t in ipairs(sometable) do
    t.name = i
end

I was then assuming print("name1", bob) would give me name1 = 1. Right now I'm getting nil. So I'm back to my ugly static list of variables till some kind soul tells me how I'm an idiot.

A: 

The ipairs function will iterate only through numerically indexed tables in ascending order.

What you want to use is the pairs function. It will iterate over every key in the table, no matter what type it is.

tjlevine
That's not the problem; the loop was fine; he should have used t[t.name] = i instead of t.name = i
Doug Currie
+3  A: 

sometable = {{name = "bob", something = "foo"},{name = "greg", something = "bar"}}

for i,t in ipairs(sometable) do t[t.name] = i end

for i,t in ipairs(sometable) do for j,u in pairs (t) do print (j,u) end end

name bob

something foo

bob 1

greg 2

something bar

name greg

return sometable[1].bob

1>

Doug Currie