Skip to content

Instantly share code, notes, and snippets.

@michlbro
Last active October 3, 2022 19:39
Show Gist options
  • Save michlbro/b72b7bfc073c3d6739b1b49de87ac3ab to your computer and use it in GitHub Desktop.
Save michlbro/b72b7bfc073c3d6739b1b49de87ac3ab to your computer and use it in GitHub Desktop.
local methodsAvilable = {else = true, except = true, finally = true}
local function MethodConstructor(fromMeta, name)
return function(func)
fromMeta.methodsCalled[name] = func
return fromMeta
end
end
local function EndResult(fromMeta, resultType, intermediateResult)
if resultType == 2 and fromMeta.methodsCalled["else"] then
fromMeta.methodsCalled["else"](table.unpack(intermediateResult))
elseif resultType == 1 or resultType == 3 and fromMeta.methodsCalled["except"] then
fromMeta.methodsCalled["except"](table.unpack(intermediateResult))
end
if fromMeta.methodsCalled["finally"] then
fromMeta.methodsCalled["finally"](table.unpack(intermediateResult))
end
fromMeta.methodsCalled = nil
fromMeta = nil
end
local function TryMethod(fromMeta, func)
local resultType, intermediateResult = 0, {}
local success, err = pcall(function()
func(function(...)
resultType = 2
intermediateResult = {...}
EndResult(fromMeta, resultType, intermediateResult)
end, function(...)
resultType = 3
intermediateResult = {...}
EndResult(fromMeta, resultType, intermediateResult)
end)
end)
if resultType > 1 then return end
EndResult(fromMeta, success and 2 or 1, {err} or intermediateResult)
end
return function(func: (resolve: any?, reject: any?) -> ())
local tryMethod = setmetatable({
methodsCalled = {}
}, {__index = function(fromMeta, index)
if methodsAvilable[index] then
return MethodConstructor(fromMeta, index)
end
end, __call = function(fromMeta, yield: boolean?)
if not yield then
print(fromMeta)
task.spawn(TryMethod, fromMeta, func)
return
end
TryMethod(fromMeta, func)
end,})
return tryMethod
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment