Search code examples
lua

how can I assign table names to variables?


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.


Solution

  • > 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>