Issue
While trying to learn lua
I accidentally found out that if
a = {"a"}
b = a
than this produces (no surprise):
a
{"a"} --[[table: 0x046bde18]]
b
{"a"} --[[table: 0x046bde18]]
but then if:
a[2] = "b"
why is a == b
still true
?
a
{"a", "b"} --[[table: 0x046bde18]]
b -- this is a surprise
{"a", "b"} --[[table: 0x046bde18]]
This seem to work both ways: if a new value is assigned to b
then it will be also assigned to a
.
On the other hand if I assign a
a value (example: a = 1
) and b = a
then if a
value is changed (a = 2
) then b
retains the original value (still b = 1
).
Questions
- Why is this behaviour different depending on wheather
a
is an array/table or a value? Is it due to built-in metatables (__newindex
)? - What is the purpose of such behaviour of arrays/tables?
- What if I wanted/needed to somehow seperate
a
andb
(or what to do if I wanted to store the values ofa
before changingb
)?
(I read Lua Assignment and Metatables and Metamethods chapters of the Lua Reference Manual but still have no clue why such behaviour occures.)