Skip to content

Instantly share code, notes, and snippets.

@JabDoesThings
Created November 14, 2024 23:30
Show Gist options
  • Select an option

  • Save JabDoesThings/84e0af1949db088e8b98680f7af6c8bf to your computer and use it in GitHub Desktop.

Select an option

Save JabDoesThings/84e0af1949db088e8b98680f7af6c8bf to your computer and use it in GitHub Desktop.
A basic coroutine example for Project Zomboid.
local IS_PZ = instanceof ~= nil;
-- Create our coroutine by passing a function to execute, from start to finish.
local thread = coroutine.create(function()
local result = 0;
for i = 0, 100, 1 do
-- Perform next pass.
result = result + i;
---------------------
-- Yield the task until resumed.
coroutine.yield();
end
-- Pass the result when yielding. This is the returned results.
coroutine.yield(result);
end);
--- @type fun(): void | nil
local onTick = nil;
--- @type string | nil
local result = nil;
onTick = function()
if coroutine.status(thread) ~= 'dead' then
-- Execute the next pass.
local success, r = coroutine.resume(thread);
-- Handle failure of the thread here.
if not success then
error(result);
if IS_PZ then
Events.OnTickEvenPaused.Remove(onTick);
end
return;
end
-- If a result is returned then assign it.
result = r;
else
print('[WARNING]: Coroutine died unexpectedly without result!!!');
if IS_PZ then
Events.OnTickEvenPaused.Remove(onTick);
end
end
-- The job is not complete.
if not result then return end
if IS_PZ then
Events.OnTickEvenPaused.Remove(onTick);
end
-- Handle result here
print('result: ' .. tostring(result));
end
-- Let PZ run each pass.
if IS_PZ then
Events.OnTickEvenPaused.Add(onTick);
-- NOTE: If you want to run the first pass immediately, call the function.
onTick();
else
-- Simulate Events tick.
while not result do
onTick();
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment