2

I have simplified my code so you can have a better understanding:

x = {}
x["foo"]=1
a = {}
a[1]=x
x["foo"]=2
a[2]=x
print(a[1]["foo"])
print(a[2]["foo"])

The result is:

2
2

Or I was expecting:

1
2

I understant that a[1] is directing at the adress of the table x["foo"]. Then, when I change the value of this table, the variable a[1] points to the new value.

How can I tell Lua that I want to assign the VALUE and not link to and adress?

And just another thing: if x is a "simple" variable, not an array, the value is passed:

y = {}
x = 1
a = {}
a[1] = x
x = 2
a[2] = x
print(a[1])
print(a[2])

returns 1 2

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
bixente57
  • 1,328
  • 4
  • 14
  • 29
  • 6
    I think you should **copy** the table. [How do you copy a Lua table by value? - Stack Overflow](http://stackoverflow.com/questions/640642/how-do-you-copy-a-lua-table-by-value) may work. – MikeCAT Sep 17 '15 at 15:05

1 Answers1

2

The Lua manual, last but one paragraph of §2.1, says:

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.

lhf
  • 70,581
  • 9
  • 108
  • 149