Last active
December 12, 2015 04:58
-
-
Save disolovyov/4718588 to your computer and use it in GitHub Desktop.
Simple classes for 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
--[[ | |
No-nonsense classes for Lua. | |
Basic usage: | |
A = class() -- class declaration | |
B = class(A) -- inheritance | |
function A:init(arg, arg ...) -- constructor | |
function A:foo(arg, arg ...) -- method declaration | |
a = A(arg, arg ...) -- construction | |
a:foo(arg, arg ...) -- method invocation | |
Setting properties: | |
A = class() | |
function A:init(x) | |
self.x = x | |
end | |
... | |
a = A() | |
print(a.x) | |
Overriding methods: | |
B = class(A) | |
... | |
function B:foo(a, b) | |
A.foo(self, a, b) | |
... | |
end | |
]] | |
local function construct(class, ...) | |
local t = {} | |
local mt = {} | |
mt.__index = class | |
setmetatable(t, mt) | |
if class.init then | |
class.init(t, ...) | |
end | |
return t | |
end | |
function class(base) | |
local t = {} | |
local mt = {__call = construct} | |
if base then | |
mt.__index = base | |
end | |
return setmetatable(t, mt) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment