0
Table1 = {"x"}
Table2 = Table1

running the code below will change the value of Table1

Table2[1] = "y"
Table1[1] is now "y" instead of "x"

What is the reason behind this? Why does this doesn't happen to other data types like variable that contains string or interger? Any benefit of this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
James Penner
  • 71
  • 1
  • 6
  • Possible duplicate of [Function/variable scope (pass by value or reference?)](https://stackoverflow.com/questions/6128152/function-variable-scope-pass-by-value-or-reference) – Dimitry May 16 '18 at 11:53

1 Answers1

1

Simple explanation:
Variable does not contain an object.
Variable contains a reference to an object.

for numbers:

Number1 = 42
-- Variable refers to an object (a number 42)
Number2 = Number1 
-- Both variables refer to the same object (a number 42)
Number2 = Number2 + 1
-- You created new object (a number 43) and made variable Number2 refer to this new object.

for tables:

Table1 = {"x"}
-- Variable refers to an object (an array containing string "x")
Table2 = Table1 
-- Both variables refer to the same object (an array containing string "x")
Table2[1] = "y"
-- You modified existing object.  You didn't create new one.
Egor Skriptunoff
  • 906
  • 1
  • 8
  • 23
  • I wanna know the reason – James Penner May 16 '18 at 09:20
  • 1
    The reason of "Why a variable does not contain an object?" is "It is by language design". Some languages copy arrays on assignment, Lua does not. It looks like it was done for the sake of conceptional simplicity. But I guess the reason is just the performance. Want to create a copy - make it yourself. – Egor Skriptunoff May 16 '18 at 09:37