Search code examples
classooplualua-table

Unable to create instance from base class in lua using metatable


I am currently working on Defold project and need to build a class in lua. This is my base class

local class = {}
class.__index = class
class.value = nil
function class.create()
    local o ={}
    setmetatable(o, class)
    return o
end
function class:printOut()
    print(class.value)
end
function class:setValue(value)
    class.value = value
end
return class

This is my usage in main script

local mclass = require "main.mclass"
local B
local C

function init(self)
    msg.post(".", "acquire_input_focus")
    msg.post("@render:", "use_fixed_fit_projection", { near = -1, far = 1 })
    B = mclass.create()
    C = mclass.create()
end

function on_input(self, action_id, action)
    if action_id == hash("touch") and action.pressed then
        B:setValue(10)
        print(B.value)
        B:setValue(12)
        print(C.value)
        --print(B.value)
    end
end

I suppose to create instance from base class for each B and C. But seem both of them point to a same base class. As I changed value by using B then value in C also got changed. Did I miss something here. Or my setup for class is wrong. Thanks for help guys !


Solution

  • In your mclass file, class always refers to the same table. That's the table that you modify/access in printOut and setValue.

    By using colon notation, both of those functions have an implicit self parameter. Use that instead of class (e.g. print(self.value) and self.value = value).