Created
April 24, 2019 15:06
-
-
Save Masterexa/5f0c20803fb9a5c4f64a237478f6648e to your computer and use it in GitHub Desktop.
Class definition in Lua
This file contains 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
-------------------- Base Class -------------------- | |
local Base = {} | |
---- Member Methods ---- | |
function Base:foo() | |
return 'foo.' | |
end | |
function Base:say() | |
io.write(self.name..' : '..self.foo()) | |
io.write('\n') | |
end | |
-- Constructor | |
function Base:init() | |
self.name = 'Luatan' | |
end | |
---- Class Method ---- | |
Base.new = function() | |
local obj = setmetatable({},{__index=Base}) | |
obj:init() | |
return obj | |
end | |
-------------------- Inherited Class -------------------- | |
-- | |
local Inherited = setmetatable({}, {__index=Base}) | |
---- Member Methods ---- | |
-- override the method | |
function Inherited:foo() | |
return '(^q^)' | |
end | |
-- Constructor | |
function Inherited:init() | |
-- Calling constructor of parent class | |
Base.init(self) | |
end | |
---- Class Method ---- | |
Inherited.new = function() | |
local obj = setmetatable({},{__index=Inherited}) | |
obj:init() | |
return obj | |
end | |
---------------------------------------------------- | |
local obj0 = Base.new() | |
local obj1 = Inherited.new() | |
obj0:say() | |
obj1:say() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment