Calling a function in two tables gives same output

Viewed 38

i recently tried out luas Pseudeo OOP Mechanics. I want to call a function inside to tables which write a value into a variable in their Tables. I tried using the self variable. Here is my Code:

local Table = {}
Table.value = 0;
  
function Table:myfunc(Parameter)
    self.value = Parameter;
end

local Table1 = Table;
local Table2 = Table;

Table1:myfunc("1");
Table2:myfunc("2");

print(Table1.value)
print(Table2.value)

The Problem is, that it prints 2 both times. If i print out the parameter iside the function, then it shows 1 and 2, exactly what i want. So what am I doing wrong?

(and sorry if im writing this in the wrong place, this is my first post here :))

Any help would be appriciated.

Greetings

1 Answers

Tables are not immutable, meaning, they are always passed by reference.

Table1 and Table2 both reference to table Table.

This code is doing the same as:

Table:myfunc("1")
Table:myfunc("2")

To solve this you need to make each table as separate instance. To use myfunc on them you need either to copy this function to each instance or create a metatable for all instances and put myfunc inside.

Solution 1:

local Table1 = {value = 0, myfunc = myfunc} -- every instance has to set this function
local Table2 = {value = 0, myfunc = myfunc}

Table1:myfunc("1")
Table2:myfunc("2")

print(Table1.value, Table2.value) -- 1    2

Solution 2:

local Meta = {myfunc = myfunc} -- create metatable
Meta.__index == Meta -- On indexing event (on tbl.var or tbl[var]) use "Meta" table

local Table1 = {value = 0}
local Table2 = {value = 0}
setmetatable(Table1, Meta) -- set metatable for the instance
setmetatable(Table2, Meta)

Table1:myfunc("1")
Table2:myfunc("2")

print(Table1.value, Table2.value) -- 1    2

Metatable's __index is used when you index a table with a key that doesn't exist, like a fallback.

This problem is explained in Lua PIL book with future explanation of metatables: https://www.lua.org/pil/16.html

Related