Skip to content

Instantly share code, notes, and snippets.

@idbrii
Last active August 28, 2022 19:46
Show Gist options
  • Save idbrii/b464563ba18fd0c44c8587748b598bfe to your computer and use it in GitHub Desktop.
Save idbrii/b464563ba18fd0c44c8587748b598bfe to your computer and use it in GitHub Desktop.
The most basic class function I can imagine.
-- public domain, CC0
-- extremely basic class.
-- only supports instances and constructors (no inheritance, mixin, etc).
-- Copypaste this function to your module to avoid depending on a class library.
local function Class()
local cls = {}
cls.__index = cls
setmetatable(cls, {
__call = function(cls_, ...)
local obj = setmetatable({}, cls)
obj:ctor(...)
return obj
end
})
return cls
end
-- Example:
local function test_Class()
local MyClass = Class()
function MyClass:ctor(a)
self.a = a
end
function MyClass:shout()
print(self.a)
end
local m = MyClass("hi")
n = MyClass("there")
m:shout() -- prints 'hi'
n:shout() -- prints 'there'
end
return Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment