How do I make this table not set to a value when function is ran?

I’ve first encountered this problem on vanilla Lua 5.3 but I also have the same problem on Roblox Lua (5.1). I want to make a function that merges the table.

function merge(t1, t2)
    for k, v in next, t2 do
        if (type(v) == "table") and (type(t1[k]) == "table") then
            t1[k] = merge(t1[k], t2[k]);
        else
            t1[k] = v;
        end;
    end;
    return t1;
end;
local a = { test = 'test1' };
local b = { test = 'test2' };
local c = a;
print(a.test);
print(merge(a, b).test);
print(a.test);
print(c.test);

It should’ve outputted

test1
test2
test1
test1

But the code somehow output the result differently:
image

This is also a problem in Roblox lua:
image

The problem is that the table ‘a’ is somehow set to the merged function when the merge function is run. I don’t want that to happen, how do I make it so both the merge function runs and the table ‘a’ isn’t changing.

Looks like Python and C have this same problem, Roblox lua isn’t alone surprisingly:
pythonproblem1
pythonproblem2

Cproblem1
CProblem2

Tables are objects, therefore passed by reference, which means when you do c = a you are making a new reference to the table a points to, and not a copy of it.

Edit: also, in function calls, you pass references to tables around, so no copies are being made.

This is intended behaviour. Python dicts are passed by reference like lists and sets and so on. In fact, everything in Python is an object. Even bools, ints, and strs!

I am still kinda learning C so I don’t know too much about pointers.

but pls return 0; pls pls int main()

1 Like