Table not working as attribute in my class

Viewed 38

I have a situation like this:

TestClass = { param = { n = 5 } }
function TestClass:new(o)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    return o
end
function TestClass:update(n)
    n = n or 1
    self.param.n = self.param.n + n
end

The issue is that when I instantiate an object like: obj = TestClass:new() the update method doesn't update the value stored in the obj table but instead it changes the value inside the default table: TestClass

Is there a way to fix this? I already looked up the tutorial by the creators of lua but they say nothing about tables as attributes.

2 Answers

I think you should do it like this then:

function TestClass:new(o)
    o = o or { param = { n = 5 } }
    setmetatable(o, self)
    self.__index = self
    return o
end

I solved this and the problem was that tables are stored by reference, not value so the solution was to create the table inside the o object at the time of instancing (the TestClass:new() method).

To do this automatically and only for params that are not passed in I wrote this little function:

function setDefaults(o, def)
    for k,v in pairs(def) do
        o[k] = o[k] or v
    end
end

And it is simply used like this:

function TestClass:new(o)
    o = o or {}
    setDefaults(o, {
        param = { n = 5 }
    })
    setmetatable(o, self)
    self.__index = self
    return o
end

I also wanted to thank a lot u/JackMacWindowsLinux and Ivo Beckers for helping me find this solution.

Related