Skip to content

Instantly share code, notes, and snippets.

@Masterexa
Created April 24, 2019 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Masterexa/5f0c20803fb9a5c4f64a237478f6648e to your computer and use it in GitHub Desktop.
Save Masterexa/5f0c20803fb9a5c4f64a237478f6648e to your computer and use it in GitHub Desktop.
Class definition in Lua
-------------------- 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