NTS716
NTS716

Reputation: 71

My Lua OOP Implementation

I'm messing around with Lua, trying to get OOP to work, ran into some issues and everything works on my end, but I want to know if I'm missing anything, or an unexpected issue will come up using this method to implement oop.

Basically I have a base class

local BaseClass = {}
function BaseClass.new()
    local self = setmetatable({}, BaseClass)
    return self
end

And then a child class

local ChildClass = {}
function ChildClass.new()
    local self = BaseClass.new()
    return self
end

Again, everything works, the childclass inherits all the members from the base class, and to my understanding methods are basically variables in lua, so it also inherits those, and then I can add specific members to childclass, and call those. So if it could be better (but still relatively lightweight), if I'll be hit with an unexpected issue or I'm doing something redundant, please let me know.

Upvotes: 1

Views: 263

Answers (1)

Oka
Oka

Reputation: 26355

You're breaking the chain. The table returned from ChildClass.new will have no association with the ChildClass table.

You'll want to take a look at Chapter 16 of Programming in Lua, which discusses a typical approach to implementing Object Oriented Programming.

What it boils down to is that you need to use the implicit self, by way of the : descriptor, if you want to maintain a chain. You don't need to manually define the ChildClass constructor, but rather let it inherit the one from BaseClass by making it an instance of sorts.

local BaseClass = {}

function BaseClass:new()
    self.__index = self
    return setmetatable({}, self)
end

local ChildClass = BaseClass:new()

Now you can define shared functions for instances of ChildClass.

function ChildClass:foo ()
    print('foo!')
end

local child_inst = ChildClass:new()
child_inst:foo()

Upvotes: 1

Related Questions