Page 1 of 1
Table in table problem
Posted: Sun May 10, 2015 7:28 pm
by likemau5
Hi guys. I want to make a table with some data, and then make few tables containing the 1st table, and then make operations on them separately(?)
So i have this:
Code: Select all
function love.load()
tab1 = {}
tab1[1] = {a=1,b=1}
tab1[2] = {a=5,b=6}
tab2 = {}
tab2[1] = {tab1 = tab1}
tab2[2] = {tab1 = tab1}
end
function love.update(dt)
tab2[2].tab1[1].a = tab2[2].tab1[1].a + 1
print("tab1 is " .. tab2[1].tab1[1].a .. "tab2 is " .. tab2[2].tab1[1].a)
end
tab[1].a changes too, i want it to work like tab2[2].tab1[1].a and tab2[1].tab1[1] are separate things? I hope you guys understand me, because english isnt my native languague :/
Re: Table in table problem
Posted: Sun May 10, 2015 7:46 pm
by s-ol
likemau5 wrote:Hi guys. I want to make a table with some data, and then make few tables containing the 1st table, and then make operations on them separately(?)
So i have this:
Code: Select all
function love.load()
tab1 = {}
tab1[1] = {a=1,b=1}
tab1[2] = {a=5,b=6}
tab2 = {}
tab2[1] = {tab1 = tab1}
tab2[2] = {tab1 = tab1}
end
function love.update(dt)
tab2[2].tab1[1].a = tab2[2].tab1[1].a + 1
print("tab1 is " .. tab2[1].tab1[1].a .. "tab2 is " .. tab2[2].tab1[1].a)
end
tab[1].a changes too, i want it to work like tab2[2].tab1[1].a and tab2[1].tab1[1] are separate things? I hope you guys understand me, because english isnt my native languague :/
lua and tables just work like that, if you want to copy a table you need to explicitly create a new table:
instead of
Code: Select all
tab2[1] = {tab1 = tab1}
tab2[2] = {tab1 = tab1}
Code: Select all
tab2[1] = {}
tab2[2] = {}
for k,v in pairs(tab1) do
tab2[1][k] = v
tab2[2][k] = v
end
Also note that your whole table setup can be shortened quite a bit like this:
Code: Select all
tab1 = {
{a=1,b=1},
{a=5,b=6}
}
tab2 = { {tab1 = {}}, {tab1 = {}} }
Re: Table in table problem
Posted: Sun May 10, 2015 7:50 pm
by BOT-Brad
The issue here is that when you set
That second tab1 is passed by reference, so will "point" back to the previous object created, not create a new one with the same values.
There are a few ways you could do this, such as use a function which will "copy" the data from the table. Link ->
http://lua-users.org/wiki/CopyTable
Re: Table in table problem
Posted: Sun May 10, 2015 8:11 pm
by likemau5
Yay thank you guys! Thats exactly what i wanted to achieve
