Page 1 of 1

Saving Tables inside Tables in Lua

Posted: Mon Jan 06, 2020 8:41 am
by Lindor
Hi,

Can you help me understanding something?
If i run the code

Code: Select all

tab = {1,3}
result = {tab}
tab = {1,4}
return result
it outputs {1, 3}, as i expected.
But if i run the code

Code: Select all

local x = 3
local tab = {}
local result = {}
for k = 2, x do
    for v = 1, k do
        tab[v] = v
    end
    result[#result+1] = tab
end
then i expected result == {{1,2},{1,2,3}}
but i got result == {{1,2,3},{1,2,3}}
(I know comparing two tables and the values of two tables are two different things in lua, it's just the shortest way to write it down here. I checked by printing the values and not by comparing.)
Where is my thinking mistake?

Re: Saving Tables inside Tables in Lua

Posted: Mon Jan 06, 2020 8:51 am
by boskid

Code: Select all

result[#result+1] = tab
This does not perform deepcopy, it only puts reference to another table. Since there is only one instance of "tab", both elements inside result will be same.

Code: Select all

local x = 3
local result = {}
for k = 2, x do
    local tab = {} -- moved into loop
    for v = 1, k do
        tab[v] = v
    end
    result[#result+1] = tab
end

Re: Saving Tables inside Tables in Lua

Posted: Mon Jan 06, 2020 9:06 am
by Lindor
Ah, i see. Thank you <3

Re: Saving Tables inside Tables in Lua

Posted: Mon Jan 06, 2020 7:38 pm
by Honktown
There's a little "gotcha" with tables I'd like to point out for OP: if you pass a table into a function, it makes sense you're editing that table... unless you change the table by doing myvar = {} or something like that. You re-assign the local variable's table, and are no longer accessing the table that was passed in. It makes sense, but I ran into that and was confused why my original table wasn't being edited inside my function, and worse, all my actions were succeeding on the local table
boskid wrote: Mon Jan 06, 2020 8:51 am

Code: Select all

result[#result+1] = tab
This does not perform deepcopy, it only puts reference to another table. Since there is only one instance of "tab", both elements inside result will be same.

Code: Select all

local x = 3
local result = {}
for k = 2, x do
    local tab = {} -- moved into loop
    for v = 1, k do
        tab[v] = v
    end
    result[#result+1] = tab
end
This is more of a Lua question than anything else, and it's about fine details - I came from programming very explicit/strict languages, and I'd probably do the "initialization" of local tab = nil outside the loop, and do a tab = {} inside the loop. Lua has some laziness to the memory operations and whatnot, so there's probably not a performance/memory difference, comparing a "local <foo>" inside and outside a loop?