Gullie667
Gullie667

Reputation: 135

Controlling Variable Scope In Lua; It's changing both Vars

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

Upvotes: 3

Views: 91

Answers (1)

Yu Hao
Yu Hao

Reputation: 122493

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.

Upvotes: 3

Related Questions