Update all code styles

This commit is contained in:
Cooldude2606
2024-09-28 01:56:54 +01:00
parent 5e2a62ab27
commit 292c1a1b68
194 changed files with 9817 additions and 9703 deletions

View File

@@ -80,13 +80,13 @@ local Async = {
-- @event on_function_complete
-- @tparam AsyncFunction async_id The function which finished execution, comparable to the return of register
-- @tparam table return_values An array representing the values returned by the completed function
on_function_complete = script.generate_event_name()
on_function_complete = script.generate_event_name(),
}
Async._metatable = {
__call = function(self, ...) Async._prototype.start_soon(self, ...) end,
__index = Async._prototype,
__class = "AsyncFunction"
__class = "AsyncFunction",
}
script.register_metatable("AsyncFunction", Async._metatable)
@@ -98,16 +98,17 @@ local on_tick_mutex = false -- It is not safe to modify the globals while this v
--- Insert an item into the priority queue
local function add_to_queue(pending)
local tick = pending.tick
for index = #async_queue, 1, -1 do
if async_queue[index].tick >= tick then
async_queue[index + 1] = pending
return
else
async_queue[index + 1] = async_queue[index]
end
end
async_queue[1] = pending
local tick = pending.tick
for index = #async_queue, 1, -1 do
if async_queue[index].tick >= tick then
async_queue[index + 1] = pending
return
else
async_queue[index + 1] = async_queue[index]
end
end
async_queue[1] = pending
end
--- Static Methods.
@@ -119,7 +120,7 @@ end
-- @treturn AsyncFunction The newly registered async function
function Async.register(func)
ExpUtil.assert_not_runtime()
ExpUtil.assert_argument_type(func, "function", 1, "func")
ExpUtil.assert_argument_type(func, "function", 1, "func")
local id = ExpUtil.get_function_name(func)
Async._functions[id] = func
@@ -135,13 +136,13 @@ end
--- Run an async function on the next tick, this is the default and can be used to bypass permission groups
-- @param ... The arguments to call the function with
function Async._prototype:start_soon(...)
assert(not on_tick_mutex, "Cannot queue new async call during execution of another")
assert(not on_tick_mutex, "Cannot queue new async call during execution of another")
assert(Async._functions[self.id], "Async function is not registered")
Async._queue_pressure[self.id] = Async._queue_pressure[self.id] + 1
async_next[#async_next + 1] = {
id = self.id,
args = {...}
args = { ... },
}
end
@@ -149,22 +150,22 @@ end
-- @tparam number ticks The number of ticks to call the function after
-- @param ... The arguments to call the function with
function Async._prototype:start_after(ticks, ...)
ExpUtil.assert_argument_type(ticks, "number", 1, "ticks")
assert(not on_tick_mutex, "Cannot queue new async call during execution of another")
ExpUtil.assert_argument_type(ticks, "number", 1, "ticks")
assert(not on_tick_mutex, "Cannot queue new async call during execution of another")
assert(Async._functions[self.id], "Async function is not registered")
Async._queue_pressure[self.id] = Async._queue_pressure[self.id] + 1
add_to_queue({
add_to_queue{
id = self.id,
args = {...},
tick = game.tick + ticks
})
args = { ... },
tick = game.tick + ticks,
}
end
--- Run an async function on the next tick if the function is not already queued, allows singleton task/thread behaviour
-- @param ... The arguments to call the function with
function Async._prototype:start_task(...)
assert(not on_tick_mutex, "Cannot queue new async call during execution of another")
assert(not on_tick_mutex, "Cannot queue new async call during execution of another")
assert(Async._functions[self.id], "Async function is not registered")
if Async._queue_pressure[self.id] > 0 then return end
self:start_soon(...)
@@ -173,9 +174,9 @@ end
--- Run an async function on this tick, then queue it based on its return value
-- @param ... The arguments to call the function with
function Async._prototype:start_now(...)
assert(not on_tick_mutex, "Cannot queue new async call during execution of another")
assert(not on_tick_mutex, "Cannot queue new async call during execution of another")
assert(Async._functions[self.id], "Async function is not registered")
local status, rtn1, rtn2 = Async._functions[self.id](...)
local status, rtn1, rtn2 = Async._functions[self.id](...)
if status == Async.status.continue then
self:start_soon(table.unpack(rtn1))
elseif status == Async.status.delay then
@@ -186,10 +187,10 @@ function Async._prototype:start_now(...)
event = Async.on_function_complete,
tick = game.tick,
async_id = self.id,
returned = rtn1
returned = rtn1,
})
else
error("Async function " .. self.id .. " returned an invalid status: " .. table.inspect(status))
else
error("Async function " .. self.id .. " returned an invalid status: " .. table.inspect(status))
end
end
@@ -198,35 +199,35 @@ end
-- @section async-status
local empty_table = setmetatable({}, {
__index = function() error("Field 'Returned' is Immutable") end
__index = function() error("Field 'Returned' is Immutable") end,
}) -- File scope to allow for reuse
--- Default status, will raise on_function_complete
-- @param ... The return value of the async call
function Async.status.complete(...)
if ... == nil then
return Async.status.complete, empty_table
end
return Async.status.complete, {...}
if ... == nil then
return Async.status.complete, empty_table
end
return Async.status.complete, { ... }
end
--- Will queue the function to be called again on the next tick using the new arguments
-- @param ... The arguments to call the function with
function Async.status.continue(...)
if ... == nil then
return Async.status.continue, empty_table
end
return Async.status.continue, {...}
if ... == nil then
return Async.status.continue, empty_table
end
return Async.status.continue, { ... }
end
--- Will queue the function to be called again on a later tick using the new arguments
-- @param ... The arguments to call the function with
function Async.status.delay(ticks, ...)
ExpUtil.assert_argument_type(ticks, "number", 1, "ticks")
if ... == nil then
return Async.status.continue, ticks, empty_table
end
return Async.status.delay, ticks, {...}
ExpUtil.assert_argument_type(ticks, "number", 1, "ticks")
if ... == nil then
return Async.status.continue, ticks, empty_table
end
return Async.status.delay, ticks, { ... }
end
--- Executes an async function and processes the return value
@@ -237,49 +238,51 @@ local function exec(pending, tick, new_next, new_queue)
pending.tick = nil
pending.args = rtn1
elseif status == Async.status.delay then
new_queue[#new_queue + 1] = pending
new_queue[#new_queue + 1] = pending
pending.tick = tick + rtn1
pending.args = rtn2
elseif status == Async.status.complete or status == nil then
elseif status == Async.status.complete or status == nil then
-- The function has finished execution, raise the custom event
Async._queue_pressure[pending.id] = Async._queue_pressure[pending.id] - 1
script.raise_event(Async.on_function_complete, {
event = Async.on_function_complete,
tick = tick,
async_id = pending.id,
returned = rtn1
returned = rtn1,
})
else
error("Async function " .. pending.id .. " returned an invalid status: " .. table.inspect(status))
else
error("Async function " .. pending.id .. " returned an invalid status: " .. table.inspect(status))
end
end
local new_next, new_queue = {}, {} -- File scope to allow for reuse
--- Each tick, run all next tick functions, then check if any in the queue need to be executed
local function on_tick()
if async_next == nil then return end
if async_next == nil then return end
local tick = game.tick
-- Execute all pending functions
-- Execute all pending functions
for index = 1, #async_next, 1 do
exec(async_next[index], tick, new_next, new_queue)
async_next[index] = nil
end
for index = #async_queue, 1, -1 do
local pending = async_queue[index]
local pending = async_queue[index]
if pending.tick > tick then
break;
end
break
end
exec(pending, tick, new_next, new_queue)
async_queue[index] = nil
end
-- Queue any functions that did not complete
for index = 1, #new_next, 1 do
-- Queue any functions that did not complete
for index = 1, #new_next, 1 do
async_next[index] = new_next[index]
new_next[index] = nil
end
for index = 1, #new_queue, 1 do
for index = 1, #new_queue, 1 do
add_to_queue(new_next[index])
new_next[index] = nil
end
@@ -287,36 +290,37 @@ end
--- On load, check the queue status and update the pressure values
function Async.on_load()
if storage.exp_async_next == nil then return end
if storage.exp_async_next == nil then return end
async_next = storage.exp_async_next
async_queue = storage.exp_async_queue
async_queue = storage.exp_async_queue
for _, pending in ipairs(async_next) do
local count = Async._queue_pressure[pending.id]
if count == nil then
log("Warning: Pending async function missing after load: " .. pending.id)
Async._functions[pending.id] = function() end -- NOP
count = 0
end
Async._queue_pressure[pending.id] = count + 1
end
if count == nil then
log("Warning: Pending async function missing after load: " .. pending.id)
Async._functions[pending.id] = function() end -- NOP
count = 0
end
Async._queue_pressure[pending.id] = count + 1
end
for _, pending in ipairs(async_queue) do
local count = Async._queue_pressure[pending.id]
if count == nil then
log("Warning: Pending async function missing after load: " .. pending.id)
Async._functions[pending.id] = function() end -- NOP
count = 0
end
Async._queue_pressure[pending.id] = count + 1
if count == nil then
log("Warning: Pending async function missing after load: " .. pending.id)
Async._functions[pending.id] = function() end -- NOP
count = 0
end
Async._queue_pressure[pending.id] = count + 1
end
end
--- On server startup initialise the storage data
function Async.on_init()
if storage.exp_async_next == nil then
storage.exp_async_next = {}
storage.exp_async_queue = {}
end
Async.on_load()
if storage.exp_async_next == nil then
storage.exp_async_next = {}
storage.exp_async_queue = {}
end
Async.on_load()
end
Async.events[defines.events.on_tick] = on_tick

View File

@@ -12,7 +12,7 @@ local concat = table.concat
local Common = {
--- A large mapping of colour rgb values by their common name
color = require("modules/exp_util/include/color")
color = require("modules/exp_util/include/color"),
}
--- Raise an error if we are not in runtime
@@ -36,22 +36,22 @@ end]]
--- Check the type of a value, also considers LuaObject.object_name and metatable.__class
--- Returns true when the check failed and an error should be raised
local function check_type(value, type_name)
local value_type = type(value) --[[@as string]]
if value_type == "userdata" then
if type_name == "userdata" then
return false, value_type
end
value_type = value.object_name
elseif value_type == "table" then
if type_name == "table" then
return false, value_type
end
local mt = getmetatable(value)
if mt and mt.__class then
value_type = mt.__class
end
end
return value == nil or value_type ~= type_name, value_type
local value_type = type(value) --[[@as string]]
if value_type == "userdata" then
if type_name == "userdata" then
return false, value_type
end
value_type = value.object_name
elseif value_type == "table" then
if type_name == "table" then
return false, value_type
end
local mt = getmetatable(value)
if mt and mt.__class then
value_type = mt.__class
end
end
return value == nil or value_type ~= type_name, value_type
end
local assert_type_fmt = "%s expected to be of type %s but got %s"
@@ -60,7 +60,7 @@ local assert_type_fmt = "%s expected to be of type %s but got %s"
-- @tparam string type_name The name of the type that value is expected to be
-- @tparam[opt=Value] string value_name The name of the value being tested, this is included in the error message
function Common.assert_type(value, type_name, value_name)
local failed, actual_type = check_type(value, type_name)
local failed, actual_type = check_type(value, type_name)
if failed then
error(assert_type_fmt:format(value_name or "Value", type_name, actual_type), 2)
end
@@ -73,7 +73,7 @@ local assert_argument_fmt = "Bad argument #%d to %s; %s expected to be of type %
-- @tparam number arg_index The index of the argument being tested, this is included in the error message
-- @tparam[opt=Argument] string arg_name The name of the argument being tested, this is included in the error message
function Common.assert_argument_type(arg_value, type_name, arg_index, arg_name)
local failed, actual_type = check_type(arg_value, type_name)
local failed, actual_type = check_type(arg_value, type_name)
if failed then
local func_name = getinfo(2, "n").name or "<anonymous>"
error(assert_argument_fmt:format(arg_index, func_name, arg_name or "Argument", type_name, actual_type), 2)
@@ -87,9 +87,9 @@ end
-- @tparam[opt=0] number player_index The player's machine to write on, -1 means all, 0 means host only
function Common.write_json(path, tbl, overwrite, player_index)
if player_index == -1 then
return game.write_file(path, game.table_to_json(tbl).."\n", not overwrite)
return game.write_file(path, game.table_to_json(tbl) .. "\n", not overwrite)
end
return game.write_file(path, game.table_to_json(tbl).."\n", not overwrite, player_index or 0)
return game.write_file(path, game.table_to_json(tbl) .. "\n", not overwrite, player_index or 0)
end
--- Clear a file by replacing its contents with an empty string
@@ -118,17 +118,17 @@ end
-- @treturn string The relative filepath of the given stack frame
function Common.safe_file_path(level)
level = level or 1
return getinfo(level+1, 'S').short_src:sub(10, -5)
return getinfo(level + 1, "S").short_src:sub(10, -5)
end
--- Returns the name of your module, this assumes your module is stored within /modules (which it is for clustorio)
-- @tparam[opt=1] number level The level of the stack to get the module of, a value of 1 is the caller of this function
-- @treturn string The name of the module at the given stack frame
function Common.get_module_name(level)
local file_within_module = getinfo((level or 1)+1, 'S').short_src:sub(18, -5)
local file_within_module = getinfo((level or 1) + 1, "S").short_src:sub(18, -5)
local next_slash = file_within_module:find("/")
if next_slash then
return file_within_module:sub(1, next_slash-1)
return file_within_module:sub(1, next_slash - 1)
else
return file_within_module
end
@@ -139,12 +139,12 @@ end
-- @tparam boolean raw When true there will not be any < > around the name
-- @treturn string The name of the function at the given stack frame or provided as an argument
function Common.get_function_name(func, raw)
local debug_info = getinfo(func, "Sn")
local safe_source = debug_info.source:find('__level__')
local debug_info = getinfo(func, "Sn")
local safe_source = debug_info.source:find("__level__")
local file_name = safe_source == 1 and debug_info.short_src:sub(10, -5) or debug_info.source
local func_name = debug_info.name or debug_info.linedefined
if raw then return file_name .. ":" .. func_name end
return "<" .. file_name .. ":" .. func_name .. ">"
if raw then return file_name .. ":" .. func_name end
return "<" .. file_name .. ":" .. func_name .. ">"
end
--- Attempt a simple autocomplete search from a set of options
@@ -175,25 +175,25 @@ end
-- @return The formated version of the value
-- @return True if value is a locale string, nil otherwise
function Common.safe_value(value)
if type(value) == "table" or type(value) == "userdata" then
if type(value) == "table" or type(value) == "userdata" then
if type(value.__self) == "userdata" or type(value) == "userdata" then
local success, rtn = pcall(function() -- some userdata doesnt contain "valid"
if value.valid then -- userdata
return "<userdata:"..value.object_name..">"
else -- invalid userdata
return "<userdata:"..value.object_name..":invalid>"
end
end)
return success and rtn or "<userdata:"..value.object_name..">"
local success, rtn = pcall(function() -- some userdata doesnt contain "valid"
if value.valid then -- userdata
return "<userdata:" .. value.object_name .. ">"
else -- invalid userdata
return "<userdata:" .. value.object_name .. ":invalid>"
end
end)
return success and rtn or "<userdata:" .. value.object_name .. ">"
elseif type(value[1]) == "string" and string.find(value[1], ".+[.].+") and not string.find(value[1], "%s") then
return value, true -- locale string
elseif tostring(value) ~= "table" then
return tostring(value) -- has __tostring metamethod
else -- plain table
else -- plain table
return value
end
elseif type(value) == "function" then -- function
return "<function:"..Common.get_function_name(value, true)..">"
return "<function:" .. Common.get_function_name(value, true) .. ">"
else -- not: table, userdata, or function
return tostring(value)
end
@@ -205,17 +205,17 @@ end
-- @param[opt] maxLineCount If table newline count exceeds provided then it will be inlined
-- @return The formated version of the value
function Common.format_any(value, tableAsJson, maxLineCount)
local formatted, is_locale_string = Common.safe_value(value)
local formatted, is_locale_string = Common.safe_value(value)
if type(formatted) == "table" and not is_locale_string then
if tableAsJson then
local success, rtn = pcall(game.table_to_json, value)
if success then return rtn end
end
local rtn = table.inspect(value, {depth=5, indent=' ', newline='\n', process=Common.safe_value})
if maxLineCount == nil or select(2, rtn:gsub("\n", "")) < maxLineCount then return rtn end
return table.inspect(value, {depth=5, indent='', newline='', process=Common.safe_value})
end
return formatted
if tableAsJson then
local success, rtn = pcall(game.table_to_json, value)
if success then return rtn end
end
local rtn = table.inspect(value, { depth = 5, indent = " ", newline = "\n", process = Common.safe_value })
if maxLineCount == nil or select(2, rtn:gsub("\n", "")) < maxLineCount then return rtn end
return table.inspect(value, { depth = 5, indent = "", newline = "", process = Common.safe_value })
end
return formatted
end
--- Format a tick value into one of a selection of pre-defined formats (short, long, clock)
@@ -229,39 +229,39 @@ function Common.format_time(ticks, format, units)
if ticks ~= nil then
-- Calculate the values to be determine the display values
local max_days, max_hours, max_minutes, max_seconds = ticks/5184000, ticks/216000, ticks/3600, ticks/60
local days, hours = max_days, max_hours-floor(max_days)*24
local minutes, seconds = max_minutes-floor(max_hours)*60, max_seconds-floor(max_minutes)*60
local max_days, max_hours, max_minutes, max_seconds = ticks / 5184000, ticks / 216000, ticks / 3600, ticks / 60
local days, hours = max_days, max_hours - floor(max_days) * 24
local minutes, seconds = max_minutes - floor(max_hours) * 60, max_seconds - floor(max_minutes) * 60
-- Calculate rhw units to be displayed
rtn_days, rtn_hours, rtn_minutes, rtn_seconds = floor(days), floor(hours), floor(minutes), floor(seconds)
if not units.days then rtn_hours = rtn_hours + rtn_days*24 end
if not units.hours then rtn_minutes = rtn_minutes + rtn_hours*60 end
if not units.minutes then rtn_seconds = rtn_seconds + rtn_minutes*60 end
if not units.days then rtn_hours = rtn_hours + rtn_days * 24 end
if not units.hours then rtn_minutes = rtn_minutes + rtn_hours * 60 end
if not units.minutes then rtn_seconds = rtn_seconds + rtn_minutes * 60 end
end
local rtn = {}
if format == "clock" then
-- Example 12:34:56 or --:--:--
if units.days then rtn[#rtn+1] = rtn_days end
if units.hours then rtn[#rtn+1] = rtn_hours end
if units.minutes then rtn[#rtn+1] = rtn_minutes end
if units.seconds then rtn[#rtn+1] = rtn_seconds end
if units.days then rtn[#rtn + 1] = rtn_days end
if units.hours then rtn[#rtn + 1] = rtn_hours end
if units.minutes then rtn[#rtn + 1] = rtn_minutes end
if units.seconds then rtn[#rtn + 1] = rtn_seconds end
return concat(rtn, ":")
elseif format == "short" then
-- Example 12d 34h 56m or --d --h --m
if units.days then rtn[#rtn+1] = rtn_days.."d" end
if units.hours then rtn[#rtn+1] = rtn_hours.."h" end
if units.minutes then rtn[#rtn+1] = rtn_minutes.."m" end
if units.seconds then rtn[#rtn+1] = rtn_seconds.."s" end
if units.days then rtn[#rtn + 1] = rtn_days .. "d" end
if units.hours then rtn[#rtn + 1] = rtn_hours .. "h" end
if units.minutes then rtn[#rtn + 1] = rtn_minutes .. "m" end
if units.seconds then rtn[#rtn + 1] = rtn_seconds .. "s" end
return concat(rtn, " ")
else
-- Example 12 days, 34 hours, and 56 minutes or -- days, -- hours, and -- minutes
if units.days then rtn[#rtn+1] = rtn_days.." days" end
if units.hours then rtn[#rtn+1] = rtn_hours.." hours" end
if units.minutes then rtn[#rtn+1] = rtn_minutes.." minutes" end
if units.seconds then rtn[#rtn+1] = rtn_seconds.." seconds" end
rtn[#rtn] = "and "..rtn[#rtn]
if units.days then rtn[#rtn + 1] = rtn_days .. " days" end
if units.hours then rtn[#rtn + 1] = rtn_hours .. " hours" end
if units.minutes then rtn[#rtn + 1] = rtn_minutes .. " minutes" end
if units.seconds then rtn[#rtn + 1] = rtn_seconds .. " seconds" end
rtn[#rtn] = "and " .. rtn[#rtn]
return concat(rtn, ", ")
end
end
@@ -277,47 +277,48 @@ function Common.format_locale_time(ticks, format, units)
if ticks ~= nil then
-- Calculate the values to be determine the display values
local max_days, max_hours, max_minutes, max_seconds = ticks/5184000, ticks/216000, ticks/3600, ticks/60
local days, hours = max_days, max_hours-floor(max_days)*24
local minutes, seconds = max_minutes-floor(max_hours)*60, max_seconds-floor(max_minutes)*60
local max_days, max_hours, max_minutes, max_seconds = ticks / 5184000, ticks / 216000, ticks / 3600, ticks / 60
local days, hours = max_days, max_hours - floor(max_days) * 24
local minutes, seconds = max_minutes - floor(max_hours) * 60, max_seconds - floor(max_minutes) * 60
-- Calculate rhw units to be displayed
rtn_days, rtn_hours, rtn_minutes, rtn_seconds = floor(days), floor(hours), floor(minutes), floor(seconds)
if not units.days then rtn_hours = rtn_hours + rtn_days*24 end
if not units.hours then rtn_minutes = rtn_minutes + rtn_hours*60 end
if not units.minutes then rtn_seconds = rtn_seconds + rtn_minutes*60 end
if not units.days then rtn_hours = rtn_hours + rtn_days * 24 end
if not units.hours then rtn_minutes = rtn_minutes + rtn_hours * 60 end
if not units.minutes then rtn_seconds = rtn_seconds + rtn_minutes * 60 end
end
local rtn = {}
local join = ", "
if format == "clock" then
-- Example 12:34:56 or --:--:--
if units.days then rtn[#rtn+1] = rtn_days end
if units.hours then rtn[#rtn+1] = rtn_hours end
if units.minutes then rtn[#rtn+1] = rtn_minutes end
if units.seconds then rtn[#rtn+1] = rtn_seconds end
if units.days then rtn[#rtn + 1] = rtn_days end
if units.hours then rtn[#rtn + 1] = rtn_hours end
if units.minutes then rtn[#rtn + 1] = rtn_minutes end
if units.seconds then rtn[#rtn + 1] = rtn_seconds end
join = { "colon" }
elseif format == "short" then
-- Example 12d 34h 56m or --d --h --m
if units.days then rtn[#rtn+1] = {"?", {"time-symbol-days-short", rtn_days}, rtn_days.."d"} end
if units.hours then rtn[#rtn+1] = {"time-symbol-hours-short", rtn_hours} end
if units.minutes then rtn[#rtn+1] = {"time-symbol-minutes-short", rtn_minutes} end
if units.seconds then rtn[#rtn+1] = {"time-symbol-seconds-short", rtn_seconds} end
if units.days then rtn[#rtn + 1] = { "?", { "time-symbol-days-short", rtn_days }, rtn_days .. "d" } end
if units.hours then rtn[#rtn + 1] = { "time-symbol-hours-short", rtn_hours } end
if units.minutes then rtn[#rtn + 1] = { "time-symbol-minutes-short", rtn_minutes } end
if units.seconds then rtn[#rtn + 1] = { "time-symbol-seconds-short", rtn_seconds } end
join = " "
else
-- Example 12 days, 34 hours, and 56 minutes or -- days, -- hours, and -- minutes
if units.days then rtn[#rtn+1] = {"days", rtn_days} end
if units.hours then rtn[#rtn+1] = {"hours", rtn_hours} end
if units.minutes then rtn[#rtn+1] = {"minutes", rtn_minutes} end
if units.seconds then rtn[#rtn+1] = {"seconds", rtn_seconds} end
rtn[#rtn] = {"", { "and" }, " ", rtn[#rtn]}
if units.days then rtn[#rtn + 1] = { "days", rtn_days } end
if units.hours then rtn[#rtn + 1] = { "hours", rtn_hours } end
if units.minutes then rtn[#rtn + 1] = { "minutes", rtn_minutes } end
if units.seconds then rtn[#rtn + 1] = { "seconds", rtn_seconds } end
rtn[#rtn] = { "", { "and" }, " ", rtn[#rtn] }
end
local joined = { "" }
for k, v in ipairs(rtn) do
joined[2*k] = v
joined[2*k+1] = join
joined[2 * k] = v
joined[2 * k + 1] = join
end
return joined
end
@@ -341,7 +342,7 @@ function Common.insert_item_stacks(items, surface, options)
-- Attempt to insert the items
for i = 1, count do
local entity = entities[((current+i-1)%count)+1]
local entity = entities[((current + i - 1) % count) + 1]
if entity.can_insert(item) then
last_entity = entity
current = current + 1
@@ -361,9 +362,9 @@ function Common.insert_item_stacks(items, surface, options)
elseif options.area then
position = surface.find_non_colliding_position_in_box(options.name, options.area, 1, true)
else
position = surface.find_non_colliding_position(options.name, {0,0}, 0, 1, true)
position = surface.find_non_colliding_position(options.name, { 0, 0 }, 0, 1, true)
end
last_entity = surface.create_entity{name = options.name, position = position, force = options.force or "neutral"}
last_entity = surface.create_entity{ name = options.name, position = position, force = options.force or "neutral" }
count = count + 1
entities[count] = last_entity

View File

@@ -40,9 +40,9 @@ FloatingText.color = require("modules/exp_util/include/color")
function FloatingText.print(surface, position, text, color)
return surface.create_entity{
text = text,
name = 'tutorial-flying-text',
name = "tutorial-flying-text",
color = color or FloatingText.color.white,
position = position
position = position,
}
end
@@ -55,12 +55,12 @@ function FloatingText.print_above_entity(entity, text, color)
local size_y = entity.bounding_box.left_top.y - entity.bounding_box.right_bottom.y
return entity.surface.create_entity{
text = text,
name = 'tutorial-flying-text',
name = "tutorial-flying-text",
color = color or FloatingText.color.white,
position = {
x = entity.position.x,
y = entity.position.y - size_y * 0.25
}
y = entity.position.y - size_y * 0.25,
},
}
end
@@ -72,12 +72,12 @@ end
function FloatingText.print_above_player(player, text, color)
return player.surface.create_entity{
text = text,
name = 'tutorial-flying-text',
name = "tutorial-flying-text",
color = color or FloatingText.color.white,
position = {
x = player.position.x,
y = player.position.y - 1.5
}
y = player.position.y - 1.5,
},
}
end
@@ -88,12 +88,12 @@ end
function FloatingText.print_as_player(player, text)
return player.surface.create_entity{
text = text,
name = 'tutorial-flying-text',
name = "tutorial-flying-text",
color = player.chat_color,
position = {
x = player.position.x,
y = player.position.y - 1.5
}
y = player.position.y - 1.5,
},
}
end
@@ -114,7 +114,7 @@ function FloatingText.create_tag(surface, position, text, color, alt_mode)
surface = surface,
color = color or FloatingText.color.white,
only_in_alt_mode = alt_mode,
target = position
target = position,
}
end
@@ -133,8 +133,8 @@ function FloatingText.create_tag_above_entity(entity, text, color, alt_mode)
target = entity,
target_offset = {
x = 0,
y = (entity.bounding_box.left_top.y - entity.bounding_box.right_bottom.y) * -0.25
}
y = (entity.bounding_box.left_top.y - entity.bounding_box.right_bottom.y) * -0.25,
},
}
end
@@ -153,8 +153,8 @@ function FloatingText.create_tag_above_player(player, text, color, alt_mode)
target = player.character,
target_offset = {
x = 0,
y = -1.5
}
y = -1.5,
},
}
end
@@ -172,8 +172,8 @@ function FloatingText.create_tag_as_player(player, text, alt_mode)
target = player.character,
target_offset = {
x = 0,
y = -1.5
}
y = -1.5,
},
}
end

View File

@@ -1,147 +1,147 @@
-- source: https://www.rapidtables.com/web/color/RGB_Color.html
return {
maroon = {r = 128, g = 0, b = 0},
dark_red = {r = 139, g = 0, b = 0},
brown = {r = 165, g = 42, b = 42},
firebrick = {r = 178, g = 34, b = 34},
crimson = {r = 220, g = 20, b = 60},
red = {r = 255, g = 0, b = 0},
tomato = {r = 255, g = 99, b = 71},
coral = {r = 255, g = 127, b = 80},
indian_red = {r = 205, g = 92, b = 92},
light_coral = {r = 240, g = 128, b = 128},
dark_salmon = {r = 233, g = 150, b = 122},
salmon = {r = 250, g = 128, b = 114},
light_salmon = {r = 255, g = 160, b = 122},
orange_red = {r = 255, g = 69, b = 0},
dark_orange = {r = 255, g = 140, b = 0},
orange = {r = 255, g = 165, b = 0},
gold = {r = 255, g = 215, b = 0},
dark_golden_rod = {r = 184, g = 134, b = 11},
golden_rod = {r = 218, g = 165, b = 32},
pale_golden_rod = {r = 238, g = 232, b = 170},
dark_khaki = {r = 189, g = 183, b = 107},
khaki = {r = 240, g = 230, b = 140},
olive = {r = 128, g = 128, b = 0},
yellow = {r = 255, g = 255, b = 0},
yellow_green = {r = 154, g = 205, b = 50},
dark_olive_green = {r = 85, g = 107, b = 47},
olive_drab = {r = 107, g = 142, b = 35},
lawn_green = {r = 124, g = 252, b = 0},
chart_reuse = {r = 127, g = 255, b = 0},
green_yellow = {r = 173, g = 255, b = 47},
dark_green = {r = 0, g = 100, b = 0},
green = {r = 0, g = 128, b = 0},
forest_green = {r = 34, g = 139, b = 34},
lime = {r = 0, g = 255, b = 0},
lime_green = {r = 50, g = 205, b = 50},
light_green = {r = 144, g = 238, b = 144},
pale_green = {r = 152, g = 251, b = 152},
dark_sea_green = {r = 143, g = 188, b = 143},
medium_spring_green = {r = 0, g = 250, b = 154},
spring_green = {r = 0, g = 255, b = 127},
sea_green = {r = 46, g = 139, b = 87},
medium_aqua_marine = {r = 102, g = 205, b = 170},
medium_sea_green = {r = 60, g = 179, b = 113},
light_sea_green = {r = 32, g = 178, b = 170},
dark_slate_gray = {r = 47, g = 79, b = 79},
teal = {r = 0, g = 128, b = 128},
dark_cyan = {r = 0, g = 139, b = 139},
aqua = {r = 0, g = 255, b = 255},
cyan = {r = 0, g = 255, b = 255},
light_cyan = {r = 224, g = 255, b = 255},
dark_turquoise = {r = 0, g = 206, b = 209},
turquoise = {r = 64, g = 224, b = 208},
medium_turquoise = {r = 72, g = 209, b = 204},
pale_turquoise = {r = 175, g = 238, b = 238},
aqua_marine = {r = 127, g = 255, b = 212},
powder_blue = {r = 176, g = 224, b = 230},
cadet_blue = {r = 95, g = 158, b = 160},
steel_blue = {r = 70, g = 130, b = 180},
corn_flower_blue = {r = 100, g = 149, b = 237},
deep_sky_blue = {r = 0, g = 191, b = 255},
dodger_blue = {r = 30, g = 144, b = 255},
light_blue = {r = 173, g = 216, b = 230},
sky_blue = {r = 135, g = 206, b = 235},
light_sky_blue = {r = 135, g = 206, b = 250},
midnight_blue = {r = 25, g = 25, b = 112},
navy = {r = 0, g = 0, b = 128},
dark_blue = {r = 0, g = 0, b = 139},
medium_blue = {r = 0, g = 0, b = 205},
blue = {r = 0, g = 0, b = 255},
royal_blue = {r = 65, g = 105, b = 225},
blue_violet = {r = 138, g = 43, b = 226},
indigo = {r = 75, g = 0, b = 130},
dark_slate_blue = {r = 72, g = 61, b = 139},
slate_blue = {r = 106, g = 90, b = 205},
medium_slate_blue = {r = 123, g = 104, b = 238},
medium_purple = {r = 147, g = 112, b = 219},
dark_magenta = {r = 139, g = 0, b = 139},
dark_violet = {r = 148, g = 0, b = 211},
dark_orchid = {r = 153, g = 50, b = 204},
medium_orchid = {r = 186, g = 85, b = 211},
purple = {r = 128, g = 0, b = 128},
thistle = {r = 216, g = 191, b = 216},
plum = {r = 221, g = 160, b = 221},
violet = {r = 238, g = 130, b = 238},
magenta = {r = 255, g = 0, b = 255},
fuchsia = {r = 255, g = 0, b = 255},
orchid = {r = 218, g = 112, b = 214},
medium_violet_red = {r = 199, g = 21, b = 133},
pale_violet_red = {r = 219, g = 112, b = 147},
deep_pink = {r = 255, g = 20, b = 147},
hot_pink = {r = 255, g = 105, b = 180},
light_pink = {r = 255, g = 182, b = 193},
pink = {r = 255, g = 192, b = 203},
antique_white = {r = 250, g = 235, b = 215},
beige = {r = 245, g = 245, b = 220},
bisque = {r = 255, g = 228, b = 196},
blanched_almond = {r = 255, g = 235, b = 205},
wheat = {r = 245, g = 222, b = 179},
corn_silk = {r = 255, g = 248, b = 220},
lemon_chiffon = {r = 255, g = 250, b = 205},
light_golden_rod_yellow = {r = 250, g = 250, b = 210},
light_yellow = {r = 255, g = 255, b = 224},
saddle_brown = {r = 139, g = 69, b = 19},
sienna = {r = 160, g = 82, b = 45},
chocolate = {r = 210, g = 105, b = 30},
peru = {r = 205, g = 133, b = 63},
sandy_brown = {r = 244, g = 164, b = 96},
burly_wood = {r = 222, g = 184, b = 135},
tan = {r = 210, g = 180, b = 140},
rosy_brown = {r = 188, g = 143, b = 143},
moccasin = {r = 255, g = 228, b = 181},
navajo_white = {r = 255, g = 222, b = 173},
peach_puff = {r = 255, g = 218, b = 185},
misty_rose = {r = 255, g = 228, b = 225},
lavender_blush = {r = 255, g = 240, b = 245},
linen = {r = 250, g = 240, b = 230},
old_lace = {r = 253, g = 245, b = 230},
papaya_whip = {r = 255, g = 239, b = 213},
sea_shell = {r = 255, g = 245, b = 238},
mint_cream = {r = 245, g = 255, b = 250},
slate_gray = {r = 112, g = 128, b = 144},
light_slate_gray = {r = 119, g = 136, b = 153},
light_steel_blue = {r = 176, g = 196, b = 222},
lavender = {r = 230, g = 230, b = 250},
floral_white = {r = 255, g = 250, b = 240},
alice_blue = {r = 240, g = 248, b = 255},
ghost_white = {r = 248, g = 248, b = 255},
honeydew = {r = 240, g = 255, b = 240},
ivory = {r = 255, g = 255, b = 240},
azure = {r = 240, g = 255, b = 255},
snow = {r = 255, g = 250, b = 250},
black = {r = 0, g = 0, b = 0},
silver = {r = 192, g = 192, b = 192},
dim_grey = {r = 105, g = 105, b = 105},
grey = {r = 128, g = 128, b = 128},
dark_grey = {r = 169, g = 169, b = 169},
light_grey = {r = 211, g = 211, b = 211},
gainsboro = {r = 220, g = 220, b = 220},
white_smoke = {r = 245, g = 245, b = 245},
white = {r = 255, g = 255, b = 255},
success = {r = 0, g = 255, b = 0},
warning = {r = 255, g = 255, b = 0},
fail = {r = 255, g = 0, b = 0},
info = {r = 255, g = 255, b = 255}
maroon = { r = 128, g = 0, b = 0 },
dark_red = { r = 139, g = 0, b = 0 },
brown = { r = 165, g = 42, b = 42 },
firebrick = { r = 178, g = 34, b = 34 },
crimson = { r = 220, g = 20, b = 60 },
red = { r = 255, g = 0, b = 0 },
tomato = { r = 255, g = 99, b = 71 },
coral = { r = 255, g = 127, b = 80 },
indian_red = { r = 205, g = 92, b = 92 },
light_coral = { r = 240, g = 128, b = 128 },
dark_salmon = { r = 233, g = 150, b = 122 },
salmon = { r = 250, g = 128, b = 114 },
light_salmon = { r = 255, g = 160, b = 122 },
orange_red = { r = 255, g = 69, b = 0 },
dark_orange = { r = 255, g = 140, b = 0 },
orange = { r = 255, g = 165, b = 0 },
gold = { r = 255, g = 215, b = 0 },
dark_golden_rod = { r = 184, g = 134, b = 11 },
golden_rod = { r = 218, g = 165, b = 32 },
pale_golden_rod = { r = 238, g = 232, b = 170 },
dark_khaki = { r = 189, g = 183, b = 107 },
khaki = { r = 240, g = 230, b = 140 },
olive = { r = 128, g = 128, b = 0 },
yellow = { r = 255, g = 255, b = 0 },
yellow_green = { r = 154, g = 205, b = 50 },
dark_olive_green = { r = 85, g = 107, b = 47 },
olive_drab = { r = 107, g = 142, b = 35 },
lawn_green = { r = 124, g = 252, b = 0 },
chart_reuse = { r = 127, g = 255, b = 0 },
green_yellow = { r = 173, g = 255, b = 47 },
dark_green = { r = 0, g = 100, b = 0 },
green = { r = 0, g = 128, b = 0 },
forest_green = { r = 34, g = 139, b = 34 },
lime = { r = 0, g = 255, b = 0 },
lime_green = { r = 50, g = 205, b = 50 },
light_green = { r = 144, g = 238, b = 144 },
pale_green = { r = 152, g = 251, b = 152 },
dark_sea_green = { r = 143, g = 188, b = 143 },
medium_spring_green = { r = 0, g = 250, b = 154 },
spring_green = { r = 0, g = 255, b = 127 },
sea_green = { r = 46, g = 139, b = 87 },
medium_aqua_marine = { r = 102, g = 205, b = 170 },
medium_sea_green = { r = 60, g = 179, b = 113 },
light_sea_green = { r = 32, g = 178, b = 170 },
dark_slate_gray = { r = 47, g = 79, b = 79 },
teal = { r = 0, g = 128, b = 128 },
dark_cyan = { r = 0, g = 139, b = 139 },
aqua = { r = 0, g = 255, b = 255 },
cyan = { r = 0, g = 255, b = 255 },
light_cyan = { r = 224, g = 255, b = 255 },
dark_turquoise = { r = 0, g = 206, b = 209 },
turquoise = { r = 64, g = 224, b = 208 },
medium_turquoise = { r = 72, g = 209, b = 204 },
pale_turquoise = { r = 175, g = 238, b = 238 },
aqua_marine = { r = 127, g = 255, b = 212 },
powder_blue = { r = 176, g = 224, b = 230 },
cadet_blue = { r = 95, g = 158, b = 160 },
steel_blue = { r = 70, g = 130, b = 180 },
corn_flower_blue = { r = 100, g = 149, b = 237 },
deep_sky_blue = { r = 0, g = 191, b = 255 },
dodger_blue = { r = 30, g = 144, b = 255 },
light_blue = { r = 173, g = 216, b = 230 },
sky_blue = { r = 135, g = 206, b = 235 },
light_sky_blue = { r = 135, g = 206, b = 250 },
midnight_blue = { r = 25, g = 25, b = 112 },
navy = { r = 0, g = 0, b = 128 },
dark_blue = { r = 0, g = 0, b = 139 },
medium_blue = { r = 0, g = 0, b = 205 },
blue = { r = 0, g = 0, b = 255 },
royal_blue = { r = 65, g = 105, b = 225 },
blue_violet = { r = 138, g = 43, b = 226 },
indigo = { r = 75, g = 0, b = 130 },
dark_slate_blue = { r = 72, g = 61, b = 139 },
slate_blue = { r = 106, g = 90, b = 205 },
medium_slate_blue = { r = 123, g = 104, b = 238 },
medium_purple = { r = 147, g = 112, b = 219 },
dark_magenta = { r = 139, g = 0, b = 139 },
dark_violet = { r = 148, g = 0, b = 211 },
dark_orchid = { r = 153, g = 50, b = 204 },
medium_orchid = { r = 186, g = 85, b = 211 },
purple = { r = 128, g = 0, b = 128 },
thistle = { r = 216, g = 191, b = 216 },
plum = { r = 221, g = 160, b = 221 },
violet = { r = 238, g = 130, b = 238 },
magenta = { r = 255, g = 0, b = 255 },
fuchsia = { r = 255, g = 0, b = 255 },
orchid = { r = 218, g = 112, b = 214 },
medium_violet_red = { r = 199, g = 21, b = 133 },
pale_violet_red = { r = 219, g = 112, b = 147 },
deep_pink = { r = 255, g = 20, b = 147 },
hot_pink = { r = 255, g = 105, b = 180 },
light_pink = { r = 255, g = 182, b = 193 },
pink = { r = 255, g = 192, b = 203 },
antique_white = { r = 250, g = 235, b = 215 },
beige = { r = 245, g = 245, b = 220 },
bisque = { r = 255, g = 228, b = 196 },
blanched_almond = { r = 255, g = 235, b = 205 },
wheat = { r = 245, g = 222, b = 179 },
corn_silk = { r = 255, g = 248, b = 220 },
lemon_chiffon = { r = 255, g = 250, b = 205 },
light_golden_rod_yellow = { r = 250, g = 250, b = 210 },
light_yellow = { r = 255, g = 255, b = 224 },
saddle_brown = { r = 139, g = 69, b = 19 },
sienna = { r = 160, g = 82, b = 45 },
chocolate = { r = 210, g = 105, b = 30 },
peru = { r = 205, g = 133, b = 63 },
sandy_brown = { r = 244, g = 164, b = 96 },
burly_wood = { r = 222, g = 184, b = 135 },
tan = { r = 210, g = 180, b = 140 },
rosy_brown = { r = 188, g = 143, b = 143 },
moccasin = { r = 255, g = 228, b = 181 },
navajo_white = { r = 255, g = 222, b = 173 },
peach_puff = { r = 255, g = 218, b = 185 },
misty_rose = { r = 255, g = 228, b = 225 },
lavender_blush = { r = 255, g = 240, b = 245 },
linen = { r = 250, g = 240, b = 230 },
old_lace = { r = 253, g = 245, b = 230 },
papaya_whip = { r = 255, g = 239, b = 213 },
sea_shell = { r = 255, g = 245, b = 238 },
mint_cream = { r = 245, g = 255, b = 250 },
slate_gray = { r = 112, g = 128, b = 144 },
light_slate_gray = { r = 119, g = 136, b = 153 },
light_steel_blue = { r = 176, g = 196, b = 222 },
lavender = { r = 230, g = 230, b = 250 },
floral_white = { r = 255, g = 250, b = 240 },
alice_blue = { r = 240, g = 248, b = 255 },
ghost_white = { r = 248, g = 248, b = 255 },
honeydew = { r = 240, g = 255, b = 240 },
ivory = { r = 255, g = 255, b = 240 },
azure = { r = 240, g = 255, b = 255 },
snow = { r = 255, g = 250, b = 250 },
black = { r = 0, g = 0, b = 0 },
silver = { r = 192, g = 192, b = 192 },
dim_grey = { r = 105, g = 105, b = 105 },
grey = { r = 128, g = 128, b = 128 },
dark_grey = { r = 169, g = 169, b = 169 },
light_grey = { r = 211, g = 211, b = 211 },
gainsboro = { r = 220, g = 220, b = 220 },
white_smoke = { r = 245, g = 245, b = 245 },
white = { r = 255, g = 255, b = 255 },
success = { r = 0, g = 255, b = 0 },
warning = { r = 255, g = 255, b = 0 },
fail = { r = 255, g = 0, b = 0 },
info = { r = 255, g = 255, b = 255 },
}

View File

@@ -1,7 +1,7 @@
local inspect = {
_VERSION = 'inspect.lua 3.1.0',
_URL = 'http://github.com/kikito/inspect.lua',
_DESCRIPTION = 'human-readable representations of tables',
_VERSION = "inspect.lua 3.1.0",
_URL = "http://github.com/kikito/inspect.lua",
_DESCRIPTION = "human-readable representations of tables",
_LICENSE = [[
MIT LICENSE
@@ -25,13 +25,13 @@ local inspect = {
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
]],
}
local tostring = tostring
inspect.KEY = setmetatable({}, {__tostring = function() return 'inspect.KEY' end})
inspect.METATABLE = setmetatable({}, {__tostring = function() return 'inspect.METATABLE' end})
inspect.KEY = setmetatable({}, { __tostring = function() return "inspect.KEY" end })
inspect.METATABLE = setmetatable({}, { __tostring = function() return "inspect.METATABLE" end })
-- Apostrophizes the string if it has quotes, but not aphostrophes
-- Otherwise, it returns a regular quoted string
@@ -44,51 +44,64 @@ end
-- \a => '\\a', \0 => '\\0', 31 => '\31'
local shortControlCharEscapes = {
["\a"] = "\\a", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n",
["\r"] = "\\r", ["\t"] = "\\t", ["\v"] = "\\v"
["\a"] = "\\a",
["\b"] = "\\b",
["\f"] = "\\f",
["\n"] = "\\n",
["\r"] = "\\r",
["\t"] = "\\t",
["\v"] = "\\v",
}
local longControlCharEscapes = {} -- \a => nil, \0 => \000, 31 => \031
for i=0, 31 do
for i = 0, 31 do
local ch = string.char(i)
if not shortControlCharEscapes[ch] then
shortControlCharEscapes[ch] = "\\"..i
longControlCharEscapes[ch] = string.format("\\%03d", i)
shortControlCharEscapes[ch] = "\\" .. i
longControlCharEscapes[ch] = string.format("\\%03d", i)
end
end
local function escape(str)
return (str:gsub("\\", "\\\\")
:gsub("(%c)%f[0-9]", longControlCharEscapes)
:gsub("%c", shortControlCharEscapes))
:gsub("(%c)%f[0-9]", longControlCharEscapes)
:gsub("%c", shortControlCharEscapes))
end
local function isIdentifier(str)
return type(str) == 'string' and str:match( "^[_%a][_%a%d]*$" )
return type(str) == "string" and str:match("^[_%a][_%a%d]*$")
end
local function isSequenceKey(k, sequenceLength)
return type(k) == 'number'
and 1 <= k
and k <= sequenceLength
and math.floor(k) == k
return type(k) == "number"
and 1 <= k
and k <= sequenceLength
and math.floor(k) == k
end
local defaultTypeOrders = {
['number'] = 1, ['boolean'] = 2, ['string'] = 3, ['table'] = 4,
['function'] = 5, ['userdata'] = 6, ['thread'] = 7
["number"] = 1,
["boolean"] = 2,
["string"] = 3,
["table"] = 4,
["function"] = 5,
["userdata"] = 6,
["thread"] = 7,
}
local function sortKeys(a, b)
local ta, tb = type(a), type(b)
-- strings and numbers are sorted numerically/alphabetically
if ta == tb and (ta == 'string' or ta == 'number') then return a < b end
if ta == tb and (ta == "string" or ta == "number") then return a < b end
local dta, dtb = defaultTypeOrders[ta], defaultTypeOrders[tb]
-- Two default types are compared according to the defaultTypeOrders table
if dta and dtb then return defaultTypeOrders[ta] < defaultTypeOrders[tb]
elseif dta then return true -- default types before custom ones
elseif dtb then return false -- custom types after default ones
if dta and dtb then
return defaultTypeOrders[ta] < defaultTypeOrders[tb]
elseif dta then
return true -- default types before custom ones
elseif dtb then
return false -- custom types after default ones
end
-- custom types are sorted out alphabetically
@@ -104,6 +117,7 @@ local function getSequenceLength(t)
len = len + 1
v = rawget(t, len)
end
return len - 1
end
@@ -113,30 +127,32 @@ local function getNonSequentialKeys(t)
for k, _ in pairs(t) do
if not isSequenceKey(k, sequenceLength) then table.insert(keys, k) end
end
table.sort(keys, sortKeys)
return keys, sequenceLength
end
local function getToStringResultSafely(t, mt)
local __tostring = type(mt) == 'table' and rawget(mt, '__tostring')
local __tostring = type(mt) == "table" and rawget(mt, "__tostring")
local str, ok
if type(__tostring) == 'function' then
if type(__tostring) == "function" then
ok, str = pcall(__tostring, t)
str = ok and str or 'error: ' .. tostring(str)
str = ok and str or "error: " .. tostring(str)
end
if type(str) == 'string' and #str > 0 then return str end
if type(str) == "string" and #str > 0 then return str end
end
local function countTableAppearances(t, tableAppearances)
tableAppearances = tableAppearances or {}
if type(t) == 'table' then
if type(t) == "table" then
if not tableAppearances[t] then
tableAppearances[t] = 1
for k, v in pairs(t) do
countTableAppearances(k, tableAppearances)
countTableAppearances(v, tableAppearances)
end
countTableAppearances(getmetatable(t), tableAppearances)
else
tableAppearances[t] = tableAppearances[t] + 1
@@ -148,43 +164,44 @@ end
local copySequence = function(s)
local copy, len = {}, #s
for i=1, len do copy[i] = s[i] end
for i = 1, len do copy[i] = s[i] end
return copy, len
end
local function makePath(path, ...)
local keys = {...}
local keys = { ... }
local newPath, len = copySequence(path)
for i=1, #keys do
for i = 1, #keys do
newPath[len + i] = keys[i]
end
return newPath
end
-- Cooldude2606: Modified this to respect the depth option
local function processRecursive(process, item, path, visited, depth)
if item == nil then return nil end
if visited[item] then return visited[item] end
if item == nil then return nil end
if visited[item] then return visited[item] end
local processed = process(item, path)
if type(processed) == "table" and (depth == nil or depth > 0) then
local processedCopy = {}
visited[item] = processedCopy
local processedKey
local processed = process(item, path)
if type(processed) == 'table' and (depth == nil or depth > 0) then
local processedCopy = {}
visited[item] = processedCopy
local processedKey
for k, v in pairs(processed) do
processedKey = processRecursive(process, k, makePath(path, k, inspect.KEY), visited, depth and depth - 1)
if processedKey ~= nil then
processedCopy[processedKey] = processRecursive(process, v, makePath(path, processedKey), visited, depth and depth - 1)
end
for k, v in pairs(processed) do
processedKey = processRecursive(process, k, makePath(path, k, inspect.KEY), visited, depth and depth - 1)
if processedKey ~= nil then
processedCopy[processedKey] = processRecursive(process, v, makePath(path, processedKey), visited, depth and depth - 1)
end
local mt = processRecursive(process, getmetatable(processed), makePath(path, inspect.METATABLE), visited, depth and depth - 1)
setmetatable(processedCopy, mt)
processed = processedCopy
end
return processed
local mt = processRecursive(process, getmetatable(processed), makePath(path, inspect.METATABLE), visited, depth and depth - 1)
setmetatable(processedCopy, mt)
processed = processedCopy
end
return processed
end
@@ -192,13 +209,13 @@ end
-------------------------------------------------------------------
local Inspector = {}
local Inspector_mt = {__index = Inspector}
local Inspector_mt = { __index = Inspector }
function Inspector:puts(...)
local args = {...}
local args = { ... }
local buffer = self.buffer
local len = #buffer
for i=1, #args do
local len = #buffer
for i = 1, #args do
len = len + 1
buffer[len] = args[i]
end
@@ -222,9 +239,9 @@ function Inspector:getId(v)
local id = self.ids[v]
if not id then
local tv = type(v)
id = (self.maxIds[tv] or 0) + 1
id = (self.maxIds[tv] or 0) + 1
self.maxIds[tv] = id
self.ids[v] = id
self.ids[v] = id
end
return tostring(id)
end
@@ -240,44 +257,44 @@ function Inspector:putTable(t)
if t == inspect.KEY or t == inspect.METATABLE then
self:puts(tostring(t))
elseif self:alreadyVisited(t) then
self:puts('<table ', self:getId(t), '>')
self:puts("<table ", self:getId(t), ">")
elseif self.level >= self.depth then
self:puts('{...}')
self:puts("{...}")
else
if self.tableAppearances[t] > 1 then self:puts('<', self:getId(t), '>') end
if self.tableAppearances[t] > 1 then self:puts("<", self:getId(t), ">") end
local nonSequentialKeys, sequenceLength = getNonSequentialKeys(t)
local mt = getmetatable(t)
local toStringResult = getToStringResultSafely(t, mt)
local mt = getmetatable(t)
local toStringResult = getToStringResultSafely(t, mt)
self:puts('{')
self:puts("{")
self:down(function()
if toStringResult then
self:puts(' -- ', escape(toStringResult))
self:puts(" -- ", escape(toStringResult))
if sequenceLength >= 1 then self:tabify() end
end
local count = 0
for i=1, sequenceLength do
if count > 0 then self:puts(', ') end
self:puts(' ')
for i = 1, sequenceLength do
if count > 0 then self:puts(", ") end
self:puts(" ")
self:putValue(t[i])
count = count + 1
end
for _, k in ipairs(nonSequentialKeys) do
if count > 0 then self:puts(', ') end
if count > 0 then self:puts(", ") end
self:tabify()
self:putKey(k)
self:puts(' = ')
self:puts(" = ")
self:putValue(t[k])
count = count + 1
end
if mt then
if count > 0 then self:puts(', ') end
if count > 0 then self:puts(", ") end
self:tabify()
self:puts('<metatable> = ')
self:puts("<metatable> = ")
self:putValue(mt)
end
end)
@@ -285,36 +302,36 @@ function Inspector:putTable(t)
if #nonSequentialKeys > 0 or mt then -- result is multi-lined. Justify closing }
self:tabify()
elseif sequenceLength > 0 then -- array tables have one extra space before closing }
self:puts(' ')
self:puts(" ")
end
self:puts('}')
self:puts("}")
end
end
function Inspector:putValue(v)
local tv = type(v)
if tv == 'string' then
if tv == "string" then
self:puts(smartQuote(escape(v)))
elseif tv == 'number' or tv == 'boolean' or tv == 'nil' or
tv == 'cdata' or tv == 'ctype' then
elseif tv == "number" or tv == "boolean" or tv == "nil" or
tv == "cdata" or tv == "ctype" then
self:puts(tostring(v))
elseif tv == 'table' then
elseif tv == "table" then
self:putTable(v)
else
self:puts('<', tv, ' ', self:getId(v), '>')
self:puts("<", tv, " ", self:getId(v), ">")
end
end
-------------------------------------------------------------------
function inspect.inspect(root, options)
options = options or {}
options = options or {}
local depth = options.depth or math.huge
local newline = options.newline or '\n'
local indent = options.indent or ' '
local depth = options.depth or math.huge
local newline = options.newline or "\n"
local indent = options.indent or " "
local process = options.process
if process then
@@ -322,14 +339,14 @@ function inspect.inspect(root, options)
end
local inspector = setmetatable({
depth = depth,
level = 0,
buffer = {},
ids = {},
maxIds = {},
newline = newline,
indent = indent,
tableAppearances = countTableAppearances(root)
depth = depth,
level = 0,
buffer = {},
ids = {},
maxIds = {},
newline = newline,
indent = indent,
tableAppearances = countTableAppearances(root),
}, Inspector_mt)
inspector:putValue(root)

View File

@@ -1,4 +1,4 @@
--luacheck:ignore global math
-- luacheck:ignore global math
local floor = math.floor
local abs = math.abs

View File

@@ -1,4 +1,4 @@
--luacheck:ignore global package
-- luacheck:ignore global package
local Clustorio = require("modules/clusterio/api")
@@ -13,7 +13,7 @@ package.lifecycle_stage = {
init = 5,
load = 6,
config_change = 7,
runtime = 8
runtime = 8,
}
--- Stores the current lifecycle stage we are in, compare values against package.lifecycle_stage
@@ -24,10 +24,10 @@ return setmetatable({
on_load = function() package.lifecycle = package.lifecycle_stage.load end,
on_configuration_changed = function() package.lifecycle = package.lifecycle_stage.config_change end,
events = {
-- TODO find a reliable way to set to runtime because currently it will desync if accessed before player joined
-- TODO find a reliable way to set to runtime because currently it will desync if accessed before player joined
[defines.events.on_player_joined_game] = function() package.lifecycle = package.lifecycle_stage.runtime end,
[Clustorio.events.on_server_startup] = function() package.lifecycle = package.lifecycle_stage.runtime end,
}
},
}, {
__index = package
__index = package,
})

View File

@@ -1,4 +1,4 @@
--luacheck:ignore global require
-- luacheck:ignore global require
local package = require("modules/exp_util/include/package")
local loaded = package.loaded
@@ -6,18 +6,18 @@ local _require = require
-- This replace function is used to avoid additional lines in stack traces during control stage
local function replace()
require = function(path)
if package.lifecycle == package.lifecycle_stage.runtime then
return loaded[path] or loaded[path:gsub(".", "/")] or error('Can only require files at runtime that have been required in the control stage.', 2)
else
return _require(path)
end
end
require = function(path)
if package.lifecycle == package.lifecycle_stage.runtime then
return loaded[path] or loaded[path:gsub(".", "/")] or error("Can only require files at runtime that have been required in the control stage.", 2)
else
return _require(path)
end
end
end
return setmetatable({
on_init = replace,
on_load = replace,
}, {
__call = _require
__call = _require,
})

View File

@@ -1,4 +1,4 @@
--luacheck:ignore global table
-- luacheck:ignore global table
local random = math.random
local floor = math.floor
@@ -42,17 +42,18 @@ function table.array_insert(tbl, start_index, values)
if start_index then
local starting_length = #tbl
local adding_length = #values
local move_to = start_index+adding_length+1
for offset = starting_length-start_index, 0, -1 do
tbl[move_to+offset] = tbl[starting_length+offset]
local move_to = start_index + adding_length + 1
for offset = starting_length - start_index, 0, -1 do
tbl[move_to + offset] = tbl[starting_length + offset]
end
start_index = start_index-1
start_index = start_index - 1
else
start_index = #tbl
end
for offset, item in ipairs(values) do
tbl[start_index+offset] = item
tbl[start_index + offset] = item
end
return tbl
@@ -125,6 +126,7 @@ function table.get_key(tbl, element)
return k
end
end
return nil
end
@@ -138,6 +140,7 @@ function table.get_index(tbl, element)
return i
end
end
return nil
end
@@ -166,9 +169,10 @@ local format_number, distance = table.deconstruct(require('util'), 'format_numbe
]]
function table.deconstruct(tbl, ...)
local values = {}
for _, key in pairs({...}) do
for _, key in pairs{ ... } do
table.insert(values, tbl[key])
end
return table.unpack(values)
end
@@ -239,7 +243,7 @@ function table.shuffle(t, rng)
local rand = rng or math.random
local iterations = #t
if iterations == 0 then
error('Not a sequential table')
error("Not a sequential table")
return
end
local j
@@ -255,19 +259,19 @@ end
-- @param x one comparator operand
-- @param y the other comparator operand
-- @return true if x logically comes before y in a list, false otherwise
local function sortFunc(x, y) --sorts tables with mixed index types.
local function sortFunc(x, y) -- sorts tables with mixed index types.
local tx = type(x)
local ty = type(y)
if tx == ty then
if type(x) == 'string' then
if type(x) == "string" then
return string.lower(x) < string.lower(y)
else
return x < y
end
elseif tx == 'number' then
return true --only x is a number and goes first
elseif tx == "number" then
return true -- only x is a number and goes first
else
return false --only y is a number and goes first
return false -- only y is a number and goes first
end
end
@@ -280,7 +284,7 @@ function table.get_values(tbl, sorted, as_string)
if not tbl then return {} end
local valueset = {}
local n = 0
if as_string then --checking as_string /before/ looping is faster
if as_string then -- checking as_string /before/ looping is faster
for _, v in pairs(tbl) do
n = n + 1
valueset[n] = tostring(v)
@@ -306,7 +310,7 @@ function table.get_keys(tbl, sorted, as_string)
if not tbl then return {} end
local keyset = {}
local n = 0
if as_string then --checking as_string /before/ looping is faster
if as_string then -- checking as_string /before/ looping is faster
for k, _ in pairs(tbl) do
n = n + 1
keyset[n] = tostring(k)
@@ -328,13 +332,17 @@ end
-- @treturn table the sorted table
function table.alphanum_sort(tbl)
local o = table.get_keys(tbl)
local function padnum(d) local dec, n = string.match(d, "(%.?)0*(.+)")
return #dec > 0 and ("%.12f"):format(d) or ("%s%03d%s"):format(dec, #n, n) end
local function padnum(d)
local dec, n = string.match(d, "(%.?)0*(.+)")
return #dec > 0 and ("%.12f"):format(d) or ("%s%03d%s"):format(dec, #n, n)
end
table.sort(o, function(a, b)
return tostring(a):gsub("%.?%d+", padnum)..("%3d"):format(#b)
< tostring(b):gsub("%.?%d+", padnum)..("%3d"):format(#a) end)
return tostring(a):gsub("%.?%d+", padnum) .. ("%3d"):format(#b)
< tostring(b):gsub("%.?%d+", padnum) .. ("%3d"):format(#a)
end)
local _tbl = {}
for _, k in pairs(o) do _tbl[k] = tbl[k] end
return _tbl
end
@@ -345,6 +353,7 @@ function table.key_sort(tbl)
local o = table.get_keys(tbl, true)
local _tbl = {}
for _, k in pairs(o) do _tbl[k] = tbl[k] end
return _tbl
end
@@ -365,7 +374,7 @@ end
end
]]
function table.binary_search(t, target)
--For some reason bit32.bnot doesn't return negative numbers so I'm using ~x = -1 - x instead.
-- For some reason bit32.bnot doesn't return negative numbers so I'm using ~x = -1 - x instead.
local lower = 1
local upper = #t
@@ -390,7 +399,7 @@ function table.binary_search(t, target)
end
-- add table-related functions that exist in base factorio/util to the 'table' table
require 'util'
require "util"
--- Similar to serpent.block, returns a string with a pretty representation of a table.
-- Notice: This method is not appropriate for saving/restoring tables. It is meant to be used by the programmer mainly while debugging a program.
@@ -400,7 +409,7 @@ require 'util'
-- process is a function which allow altering the passed object before transforming it into a string.
-- A typical way to use it would be to remove certain values so that they don't appear at all.
-- return <string> the prettied table
table.inspect = require 'modules.exp_util.include.inspect' --- @dep modules.exp_util.includes.inspect
table.inspect = require "modules.exp_util.include.inspect" --- @dep modules.exp_util.includes.inspect
--- Takes a table and returns the number of entries in the table. (Slower than #table, faster than iterating via pairs)
table.size = table_size

View File

@@ -55,7 +55,7 @@ function Storage.register(tbl, callback)
Storage.registered[name] = {
init = tbl,
callback = callback
callback = callback,
}
end
@@ -63,16 +63,16 @@ end
-- @tparam string name The name of the metatable to register, must be unique within your module
function Storage.register_metatable(name, tbl)
local module_name = ExpUtil.get_module_name(2)
script.register_metatable(module_name.."."..name, tbl)
script.register_metatable(module_name .. "." .. name, tbl)
end
--- Restore aliases on load, we do not need to initialise data during this event
function Storage.on_load()
local exp_storage = storage.exp_storage
if exp_storage == nil then return end
for name, info in pairs(Storage.registered) do
if exp_storage == nil then return end
for name, info in pairs(Storage.registered) do
if exp_storage[name] ~= nil then
info.callback(exp_storage[name])
info.callback(exp_storage[name])
end
end
end
@@ -94,7 +94,7 @@ function Storage.on_init()
end
Storage.events = {
[Clustorio.events.on_server_startup] = Storage.on_init
[Clustorio.events.on_server_startup] = Storage.on_init,
}
return Storage