3

I don't under stand why lua is changing both variables even though my understanding is that the one out side the functions should not be touched.

What is going on and how do I keep the 'attacker' variable unchanged?

Thanks!

local attacker = { 0,-1 }

local function test()

    local hitPattern = attacker

    print( "----------->> attacker", # attacker )

    --Set Loop Method
    if hitPattern[ # hitPattern ] == -1 then
        hitPattern[ # hitPattern ] = nil
    end

    print( "----->> attacker", # attacker )

end
test()
----------->> attacker 2
----->> attacker 1
Gullie667
  • 133
  • 11

1 Answers1

4

From Lua 5.2 reference manual:

Tables, functions, threads, and (full) userdata values are objects: variables do not actually contain these values, only references to them. Assignment, parameter passing, and function returns always manipulate references to such values; these operations do not imply any kind of copy.

So, when you assign:

local hitPattern = attacker

The variables hitPattern and attacker both reference to the same table, when you modify one, the other change as well.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • So, how can I fix this? I want a copy of the table, not a reference to it. Will I need to create a for loop and 'rebuild' another table? – Gullie667 May 22 '14 at 01:40
  • @user3660167 Yes, see [How do you copy a Lua table by value?](http://stackoverflow.com/questions/640642/how-do-you-copy-a-lua-table-by-value) – Yu Hao May 22 '14 at 03:27