Created
April 3, 2020 22:27
-
-
Save olueiro/13c729d1704fdce0448c972262f5d26b to your computer and use it in GitHub Desktop.
Lua class with safe sentinel
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
--[==[ | |
(c) 2020 MIT licensed | |
Usage example: | |
local class = require("class") | |
-- local class = require("class").safe() -- add .safe() on require to make class safe (Lua pcall is wrapped in each class function) | |
local my_class = class.new(start_param_1, start_param_2 --[[, ...]]) | |
-- local my_class = class(--[[, ...]]) -- .new is optional | |
my_class:my_method(param_1, param_2, --[[, ...]]) | |
print(my_class.my_value) | |
--]==] | |
local unpack = table.unpack or unpack | |
local remove = table.remove | |
local _fail = fail -- luacheck: ignore | |
local class = {} | |
class.__index = class | |
-- STATIC METHODS | |
class.safe = function() | |
for key, value in pairs(class) do | |
if type(value) == "function" then | |
class[key] = function(...) | |
local result = {pcall(value, ...)} | |
if remove(result, 1) then | |
return unpack(result) | |
else | |
return _fail, unpack(result) | |
end | |
end | |
end | |
end | |
return class | |
end | |
function class.new(start_param_sample) | |
local self = setmetatable({}, class) | |
self.value_sample = start_param_sample | |
return self | |
end | |
setmetatable(class, { | |
__call = function(self, ...) | |
return self.new(...) | |
end | |
}) | |
-- METHODS | |
function class:method_sample(param_sample) | |
self.value_sample = assert(param_sample) | |
end | |
return class |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment