1
0
mirror of https://github.com/ComfyFactory/ComfyFactorio.git synced 2025-01-16 02:47:48 +02:00
ComfyFactorio/utils/global.lua

94 lines
2.2 KiB
Lua
Raw Normal View History

2019-03-10 00:14:30 +02:00
local Event = require 'utils.event_core'
2022-07-10 19:41:21 +02:00
local Global = {
names = {},
index = 0,
filepath = {}
}
2018-09-19 06:51:25 +02:00
storage.tokens = {}
2020-06-24 12:40:18 +02:00
local concat = table.concat
2021-04-04 13:51:27 +02:00
--- Validates if a global table exists
--- Returns a new table index if original table exists.
---@param filepath string
---@return string
local function validate_entry(filepath)
if storage.tokens[filepath] then
if not storage.tokens[filepath].token_index then
storage.tokens[filepath].token_index = 1
else
storage.tokens[filepath].token_index = storage.tokens[filepath].token_index + 1
end
local index = storage.tokens[filepath].token_index
filepath = filepath .. '_' .. index
end
return filepath
end
2022-07-10 19:41:21 +02:00
--- Sets a new global
---@param tbl any
---@return integer
---@return string
function Global.set_global(tbl)
local filepath = debug.getinfo(3, 'S').source:match('^@__level__/(.+)$'):sub(1, -5):gsub('/', '_')
filepath = validate_entry(filepath)
2022-07-10 19:41:21 +02:00
Global.index = Global.index + 1
Global.filepath[filepath] = Global.index
Global.names[filepath] = concat { Global.filepath[filepath], ' - ', filepath }
2022-07-10 19:41:21 +02:00
storage.tokens[filepath] = tbl
2019-03-10 00:14:30 +02:00
2022-07-10 19:41:21 +02:00
return Global.index, filepath
end
--- Gets a global from global
---@param token number|string
---@return any|nil
function Global.get_global(token)
if storage.tokens[token] then
return storage.tokens[token]
end
2022-07-10 19:41:21 +02:00
end
function Global.register(tbl, callback)
local token, filepath = Global.set_global(tbl)
2020-06-24 12:40:18 +02:00
2019-03-10 00:14:30 +02:00
Event.on_load(
function ()
if storage.tokens[token] then
2022-07-10 19:41:21 +02:00
callback(Global.get_global(token))
else
2022-07-10 19:41:21 +02:00
callback(Global.get_global(filepath))
end
2019-03-10 00:14:30 +02:00
end
)
2022-07-10 19:41:21 +02:00
return filepath
2018-09-19 06:51:25 +02:00
end
function Global.register_init(tbl, init_handler, callback)
2022-07-10 19:41:21 +02:00
local token, filepath = Global.set_global(tbl)
2020-06-24 12:40:18 +02:00
2019-03-10 00:14:30 +02:00
Event.on_init(
function ()
2019-03-10 00:14:30 +02:00
init_handler(tbl)
callback(tbl)
end
)
2018-09-19 06:51:25 +02:00
2019-03-10 00:14:30 +02:00
Event.on_load(
function ()
if storage.tokens[token] then
2022-07-10 19:41:21 +02:00
callback(Global.get_global(token))
else
2022-07-10 19:41:21 +02:00
callback(Global.get_global(filepath))
end
2018-09-19 06:51:25 +02:00
end
2019-03-10 00:14:30 +02:00
)
2022-07-10 19:41:21 +02:00
return filepath
2019-03-10 00:14:30 +02:00
end
2018-09-19 06:51:25 +02:00
return Global