Last active
August 28, 2022 19:46
-
-
Save idbrii/b464563ba18fd0c44c8587748b598bfe to your computer and use it in GitHub Desktop.
The most basic class function I can imagine.
This file contains 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
-- 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