0
Assertion = {
    key
}

print(Assertion.key)

function Assertion:brl(ky)
    self.key = ky
end

v = Assertion
v:brl(5)

print(Assertion.key)
print(v.key)

Output

nil
5
5

So my question is even though I have changed only 'v.key' why has 'Assertion.key' also changed?

Anon
  • 116
  • 2
  • 6

1 Answers1

0
v = Assertion

after this line v refers to Assertion. Assertion = {} wil create a new table and store a reference to that table in the variable Assertion. Assertion does not contain that table. v = Assertion` will just create a second reference to that table. It will not copy the table nor any of its contents.

So v:brl(5) is equivalent to Assertion:brl(5). v.key is the very same value as Assertion.v

From the Lua 5.4 Reference Manual 2.1 Values and Types:

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.

If you want to make an actual copy of a table value read this

How do you copy a Lua table by value?

If you're interested in OOP you might want to give this a read

https://www.lua.org/pil/16.html

http://lua-users.org/wiki/ObjectOrientedProgramming

Just in case you want mutliple objects share the same functions

Piglet
  • 27,501
  • 3
  • 20
  • 43
  • Can you also please tell me how do I make 'v' a new object like Assertion in itself? Thank you! – Anon Feb 27 '21 at 10:45