Skip to content

Instantly share code, notes, and snippets.

@ochaton
Created May 1, 2025 12:56
Show Gist options
  • Save ochaton/458e06631d0d0b34c6d5804070aa921f to your computer and use it in GitHub Desktop.
Save ochaton/458e06631d0d0b34c6d5804070aa921f to your computer and use it in GitHub Desktop.
base.lua - compact base oop, inheritance is a main banger
local setmetatable, type, pairs, rawget = setmetatable, type, pairs, rawget
local copy do
pcall(require, 'table.new')
local table_new = rawget(table, 'new') or function(_, _) return {} end
function copy(t)
local new_t = table_new(0, 8)
for k, v in pairs(t) do new_t[k] = v end
return new_t
end
end
---@class Base
---@field super Base parent class
---@field private __type string name of the class
---@field public is fun():Base returns class itself
local base = { __type = "Base" }
base.__index = base
---Creates a subclass of the class.
---@param name string
---@return Base
function base:extend(name)
assert(type(name) == 'string', 'name must be a string')
local child = setmetatable(copy(self), self)
child.__type = name
child.__index = child
child.super = self
child.is = function() return child end
return child
end
---Construct a new instance of the class.
---@return Base
function base:new(...)
local obj = setmetatable({}, self)
obj:_init(...)
return obj
end
---Returns class-ancestor identified by name
---@param t string|Base
---@return Base?
function base:as(t)
if type(t) ~= 'string' then t = t.__type end
while type(self) == 'table' and self.__type ~= t do
self = self.super
end
return self
end
---User-defined constructor of the class.
function base._init(...) end
return base
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment