Skip to content

Instantly share code, notes, and snippets.

@disolovyov
Last active December 12, 2015 04:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save disolovyov/4718588 to your computer and use it in GitHub Desktop.
Save disolovyov/4718588 to your computer and use it in GitHub Desktop.
Simple classes for Lua
--[[
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