Created
April 8, 2021 23:22
-
-
Save arnoson/d08f768651c5f10f37cbf42210791567 to your computer and use it in GitHub Desktop.
Lua class helper
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
-- Inspired by: lua-users.org/wiki/SimpleLuaClasses | |
function class(base) | |
local c = {} | |
-- Inherit base by making a shallow copy. | |
if type(base) == 'table' then | |
for key,value in pairs(base) do c[key] = value end | |
c._base = base | |
end | |
c.__index = c | |
local mt = {} | |
-- Expose a constructor which can be called by <classname>(<args>). | |
mt.__call = function(table, ...) | |
local instance = {} | |
setmetatable(instance, c) | |
if table.init then table.init(instance, ...) end | |
return instance | |
end | |
setmetatable(c, mt) | |
return c | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment