A framework for the Godot engine to create TTRPG games for Advanced 5th Edition, Pathfinder 2nd Edition, and more
at main 47 lines 1.2 kB view raw
1-- class.lua 2-- Compatible with Lua 5.1 (not 5.0). 3function class(base, init) 4 local c = {} -- a new class instance 5 if not init and type(base) == 'function' then 6 init = base 7 base = nil 8 elseif type(base) == 'table' then 9 -- our new class is a shallow copy of the base class! 10 for i,v in pairs(base) do 11 c[i] = v 12 end 13 c._base = base 14 end 15 -- the class will be the metatable for all its objects, 16 -- and they will look up their methods in it. 17 c.__index = c 18 19 -- expose a constructor which can be called by <classname>(<args>) 20 local mt = {} 21 mt.__call = function(class_tbl, ...) 22 local obj = {} 23 setmetatable(obj,c) 24 if init then 25 init(obj,...) 26 else 27 -- make sure that any stuff from the base class is initialized! 28 if base and base.init then 29 base.init(obj, ...) 30 end 31 end 32 return obj 33 end 34 c.init = init 35 c.is_a = function(self, klass) 36 local m = getmetatable(self) 37 while m do 38 if m == klass then return true end 39 m = m._base 40 end 41 return false 42 end 43 setmetatable(c, mt) 44 return c 45end 46 47return class