Created
July 2, 2021 17:18
-
-
Save Zbizu/c0f5e1831755c1741ff7948db9407fcf to your computer and use it in GitHub Desktop.
reload safe addEvent loop example
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
-- configuration | |
LOOP_EVENT_DELAY = 5 * 1000 -- (in milliseconds) | |
-- register list of affected creatures and protect them from reload | |
if not LOOP_EVENT_REGISTERED_CREATURES then | |
LOOP_EVENT_REGISTERED_CREATURES = {} | |
end | |
-- store session id to reload the loop without duplicating it | |
if LOOP_EVENT_SESSION_ID then | |
LOOP_EVENT_SESSION_ID = LOOP_EVENT_SESSION_ID + 1 | |
else | |
LOOP_EVENT_SESSION_ID = 0 | |
end | |
-- register login event and prevent it from duplicating | |
if not LOOP_EVENT_LOGIN then | |
LOOP_EVENT_LOGIN = CreatureEvent("globalLoopEventLogin") | |
LOOP_EVENT_LOGIN:type("login") | |
function LOOP_EVENT_LOGIN.onLogin(player) | |
if LOOP_EVENT_REGISTERED_CREATURES then | |
LOOP_EVENT_REGISTERED_CREATURES[player:getId()] = true | |
end | |
return true | |
end | |
LOOP_EVENT_LOGIN:register() | |
end | |
function globalLoopEvent(sessionId) | |
-- reload happened, another loop will launch now | |
if sessionId ~= LOOP_EVENT_SESSION_ID then | |
print("Event was reloaded. Ending the function to avoid duplicates.") | |
return | |
end | |
-- loop through all registered creatures, remove unavailables | |
for cid, _ in pairs(LOOP_EVENT_REGISTERED_CREATURES) do | |
local creature = Creature(cid) | |
if creature then | |
print(creature:getName() .. " (id: " .. cid .. ") checked!") | |
else | |
print("Creature with id " .. cid .. " was not found. Removing from the list.") | |
LOOP_EVENT_REGISTERED_CREATURES[cid] = nil | |
end | |
end | |
addEvent(globalLoopEvent, LOOP_EVENT_DELAY, sessionId) | |
end | |
globalLoopEvent(LOOP_EVENT_SESSION_ID) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
note: if you intend to have multiple events, the names of functions and variables should be different so the events won't overwrite each other