Lua assign value problem

Hi,
Lately after I updated Defold, I found that some problems. I have an example of what happening:
If a have a vector A
local A = vmath.vector3(1, 1, 0)
local B = A

B.x = B.x + 1 or something … —> it affected A too: A became (2, 1, 0), not (1, 1, 0) anymore

Same with other datatype like table, …

It drives me crazy. Anh I don’t understand why ? It never happened before.
Please help me. Thanks

This is not a bug. It’s how Lua works.

Lua objects (tables, userdata objects, like vector3s and functions) are not stored as values in variables, but as references, so this is expected behaviour—your two variables A and B will point to the same vector3 object.

Also note that comparison of some of these objects does not look at the content but at the object itself, so:

local a = {}
local b = {}
print(a == b) // --> false

but (for convenience):

local a = vmath.vector3(1, 2, 3)
local b = vmath.vector3(1, 2, 3)
print(a == b) // --> true
1 Like

Also for convenience, you can use the vector3 function to create a new vector with the same values as another vector. So if you do:

local a = vmath.vector3(1, 1, 0)
local b = vmath.vector3(a)

. . . then it will behave as you want: changing one will not affect the other.

2 Likes

Thanks Defold team.
How can I do this:
Table A = Table B
Insert more value to Table A and not affect Table B. Because I want use B for other thing to do.

Could you give me a solution for nested table?. I’m so thankful for your help.

You can do

local A = table.copy(B)

That will perform a shallow copy of the table. If you have any nested tables, they won’t get copied, but left as the same reference.
For nested tables you need a recursive deep copy.
Here is some info on that http://lua-users.org/wiki/CopyTable

3 Likes

What you’re looking for is a function to make a deep copy of a Lua table. There are multiple solutions provided on the Lua user wiki, with this being one of the them (beware of deep tables or tables with circular refs as this is a recursive function):

function deepcopy(orig)
    local orig_type = type(orig)
    local copy
    if orig_type == 'table' then
        copy = {}
        for orig_key, orig_value in next, orig, nil do
            copy[deepcopy(orig_key)] = deepcopy(orig_value)
        end
        setmetatable(copy, deepcopy(getmetatable(orig)))
    else -- number, string, boolean, etc
        copy = orig
    end
    return copy
end
5 Likes

Thanks you all. I appreciate your help.

5 Likes

Thanks britzl, you always help me. Thank you.

2 Likes