Skip to content

Instantly share code, notes, and snippets.

@Aloroid
Last active January 28, 2023 08:51
Show Gist options
  • Save Aloroid/4fbc656ec215c40d21ec056b0aaa997f to your computer and use it in GitHub Desktop.
Save Aloroid/4fbc656ec215c40d21ec056b0aaa997f to your computer and use it in GitHub Desktop.
This hook allows for developers to execute asynchronous code inside Matter that will return a result at a later time.
local useHookState = Matter.useHookState
local function async<T..., R...>(callback: (T...) -> (R...), discriminator: string?): (T...) -> (boolean, R...)
local existing = useHookState(discriminator, function(existing)
if existing.task then
task.close(existing.task)
end
end)
return function(...)
local gotta_run = existing == nil
or select("#", ...) ~= existing.last_dependencies_length
if gotta_run == false then
for i = 1, select("#", ...) do
if select(i, ...) ~= existing.last_dependencies[i] then
gotta_run = true
break
end
end
end
if gotta_run then
if existing.task then
task.close(existing.task)
end
existing.last_dependencies = {...}
existing.last_dependencies_length = select("#", ...)
existing.results = {}
existing.finished = false
existing.task = task.spawn(function(...)
existing.results = {callback(...)}
existing.finished = true
end, ...)
end
return existing.finished, unpack(existing.results or {})
end
end
return async
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment