Created
March 27, 2023 05:41
-
-
Save e-skri/b8397e2afe2f695289f78b92639a70fa to your computer and use it in GitHub Desktop.
A very simple OOP implementation in Lua
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-------- Simple Lua OOP | |
local BaseClass = {} | |
BaseClass.class = BaseClass | |
function BaseClass:init(...) | |
end | |
function BaseClass:new(...) | |
local instance = setmetatable({}, {__index = self}) | |
instance:init(...) | |
return instance | |
end | |
function BaseClass:instanceOf(class) | |
if self.class == class then | |
return true | |
end | |
if self.super then | |
return self.super:instanceOf(class) | |
end | |
return false | |
end | |
function BaseClass:createSubClass() | |
local SubClass = {} | |
SubClass.class = SubClass | |
SubClass.super = self | |
return setmetatable(SubClass, {__index = self}) | |
end | |
-------- Usage Example | |
local Animal = BaseClass:createSubClass() | |
local numAnimals = 0 | |
function Animal:init(name) | |
-- self = the instance to be initialized | |
self.name = name | |
numAnimals = numAnimals + 1 | |
self.id = numAnimals | |
end | |
local Cat = Animal:createSubClass() | |
function Cat:init(name, breed) | |
-- self = the instance to be initialized | |
-- self.super = the parent class of the class of the instance | |
self.super.init(self, name) | |
self.breed = breed | |
end | |
local cat = Cat:new("cat name", "cat breed") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment