I'm fairly new to Lua and I am trying to get a class system to work. What I would like to do it to have a base class which has a bunch of properties and then extend this class for objects such as buttons, textboxes, etc.
The base class will have properties such as x, y, width, height etc and then the other classes will have, say, label or colour or similar.
If I create a function such as render() on the base class, and try to override this function later on, it doesn't seem to work. (Presumably I'm using classes completely wrong!)
Here is a reproduction down example of what I am using:
Base = {}
Base.__index = Base
function Base.create(value)
local b = {}
setmetatable(b, Base)
b.value = value
return b
end
function Base:render()
print("I'm the base! : "..self.value)
end
Button = {}
Button.__index = Base
function Button.create(value)
local b = Base.create(value)
setmetatable(b, Button)
return b
end
function Button:render()
print("I'm a button! : "..self.value)
end
Button.create("TestBtn"):render()
What I would like the Button.create("TestBtn"):render() do is to print I'm a button! : TestBtn however it prints I'm the base! : TestBtn.
Could someone help me to override the original render function with this new one?
Thanks, Will.
Button.__index = Baseis incorrect. Notice how that's the same asBase.__index = BaseButtontoBase. The issue is that you aren't usingButtonitself as__indexon anything. You need tosetmetatable(b, {__index = Button})inButton.createI believe. Sorry about that.Button.__index = Buttonactually was correct. This makes the methods defined in theButtonclass available to the objects created inButton.create(Buttonis used both as the metatable for button objects and as the table holding the button methods). What was missing is the inheritance link between base class and derived class:setmetatable(Button, Base)!