1
0
mirror of https://github.com/Refactorio/RedMew.git synced 2024-12-04 09:42:30 +02:00
RedMew/utils/token.lua

56 lines
1.2 KiB
Lua
Raw Permalink Normal View History

2018-04-07 01:24:30 +02:00
local Token = {}
2018-04-06 23:51:17 +02:00
local tokens = {}
2018-05-20 17:28:54 +02:00
local counter = 0
2018-04-06 23:51:17 +02:00
--- Assigns a unquie id for the given var.
-- This function cannot be called after on_init() or on_load() has run as that is a desync risk.
-- Typically this is used to register functions, so the id can be stored in the global table
-- instead of the function. This is because closures cannot be safely stored in the global table.
-- @param var<any>
-- @return number the unique token for the variable.
2018-04-06 23:51:17 +02:00
function Token.register(var)
if _LIFECYCLE == 8 then
error('Calling Token.register after on_init() or on_load() has run is a desync risk.', 2)
end
2018-05-20 17:28:54 +02:00
counter = counter + 1
2018-04-06 23:51:17 +02:00
2018-05-20 17:28:54 +02:00
tokens[counter] = var
2018-04-06 23:51:17 +02:00
2018-05-20 17:28:54 +02:00
return counter
2018-04-06 23:51:17 +02:00
end
function Token.get(token_id)
return tokens[token_id]
end
storage.tokens = {}
2018-05-16 12:37:22 +02:00
function Token.register_global(var)
local c = #storage.tokens + 1
2018-05-16 12:37:22 +02:00
storage.tokens[c] = var
2018-05-16 12:37:22 +02:00
return c
end
function Token.get_global(token_id)
return storage.tokens[token_id]
2018-05-16 12:37:22 +02:00
end
2018-06-17 12:39:55 +02:00
function Token.set_global(token_id, var)
storage.tokens[token_id] = var
2018-06-17 12:39:55 +02:00
end
2018-05-20 17:28:54 +02:00
local uid_counter = 0
function Token.uid()
uid_counter = uid_counter + 1
return uid_counter
end
return Token