mirror of
https://github.com/PHIDIAS0303/ExpCluster.git
synced 2025-12-30 20:41:41 +09:00
Move files to exp_legacy
This commit is contained in:
164
exp_legacy/module/overrides/debug.lua
Normal file
164
exp_legacy/module/overrides/debug.lua
Normal file
@@ -0,0 +1,164 @@
|
||||
-- localised functions
|
||||
local format = string.format
|
||||
local match = string.match
|
||||
local gsub = string.gsub
|
||||
local serialize = serpent.line
|
||||
local debug_getupvalue = debug.getupvalue
|
||||
|
||||
-- this
|
||||
local Debug = {}
|
||||
|
||||
global.debug_message_count = 0
|
||||
|
||||
---@return number next index
|
||||
local function increment()
|
||||
local next = global.debug_message_count + 1
|
||||
global.debug_message_count = next
|
||||
|
||||
return next
|
||||
end
|
||||
|
||||
--- Takes the table output from debug.getinfo and pretties it
|
||||
local function cleanup_debug(debug_table)
|
||||
local short_src = match(debug_table.source, '/[^/]*/[^/]*$')
|
||||
-- require will not return a valid string so short_src may be nil here
|
||||
if short_src then
|
||||
short_src = gsub(short_src, '%.lua', '')
|
||||
end
|
||||
|
||||
return format('[function: %s file: %s line number: %s]', debug_table.name, short_src, debug_table.currentline)
|
||||
end
|
||||
|
||||
---Shows the given message if debug is enabled. Uses serpent to print non scalars.
|
||||
-- @param message <table|string|number|boolean>
|
||||
-- @param trace_levels <number|nil> levels of stack trace to give, defaults to 1 level if nil
|
||||
function Debug.print(message, trace_levels)
|
||||
if not _DEBUG then
|
||||
return
|
||||
end
|
||||
|
||||
if not trace_levels then
|
||||
trace_levels = 2
|
||||
else
|
||||
trace_levels = trace_levels + 1
|
||||
end
|
||||
|
||||
local traceback_string = ''
|
||||
if type(message) ~= 'string' and type(message) ~= 'number' and type(message) ~= 'boolean' then
|
||||
message = serialize(message)
|
||||
end
|
||||
|
||||
message = format('[%d] %s', increment(), tostring(message))
|
||||
|
||||
if trace_levels >= 2 then
|
||||
for i = 2, trace_levels do
|
||||
local debug_table = debug.getinfo(i)
|
||||
if debug_table then
|
||||
traceback_string = format('%s -> %s', traceback_string, cleanup_debug(debug_table))
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
message = format('%s - Traceback%s', message, traceback_string)
|
||||
end
|
||||
|
||||
if _LIFECYCLE == _STAGE.runtime then
|
||||
game.print(message)
|
||||
end
|
||||
log(message)
|
||||
end
|
||||
|
||||
local function get(obj, prop)
|
||||
return obj[prop]
|
||||
end
|
||||
|
||||
local function get_lua_object_type_safe(obj)
|
||||
local s, r = pcall(get, obj, 'help')
|
||||
|
||||
if not s then
|
||||
return
|
||||
end
|
||||
|
||||
return r():match('Lua%a+')
|
||||
end
|
||||
|
||||
--- Returns the value of the key inside the object
|
||||
-- or 'InvalidLuaObject' if the LuaObject is invalid.
|
||||
-- or 'InvalidLuaObjectKey' if the LuaObject does not have an entry at that key
|
||||
-- @param object <table> LuaObject or metatable
|
||||
-- @param key <string>
|
||||
-- @return <any>
|
||||
function Debug.get_meta_value(object, key)
|
||||
if Debug.object_type(object) == 'InvalidLuaObject' then
|
||||
return 'InvalidLuaObject'
|
||||
end
|
||||
|
||||
local suc, value = pcall(get, object, key)
|
||||
if not suc then
|
||||
return 'InvalidLuaObjectKey'
|
||||
end
|
||||
|
||||
return value
|
||||
end
|
||||
|
||||
--- Returns the Lua data type or the factorio LuaObject type
|
||||
-- or 'NoHelpLuaObject' if the LuaObject does not have a help function
|
||||
-- or 'InvalidLuaObject' if the LuaObject is invalid.
|
||||
-- @param object <any>
|
||||
-- @return string
|
||||
function Debug.object_type(object)
|
||||
local obj_type = type(object)
|
||||
|
||||
if obj_type ~= 'table' or type(object.__self) ~= 'userdata' then
|
||||
return obj_type
|
||||
end
|
||||
|
||||
local suc, valid = pcall(get, object, 'valid')
|
||||
if not suc then
|
||||
-- no 'valid' property
|
||||
return get_lua_object_type_safe(object) or 'NoHelpLuaObject'
|
||||
end
|
||||
|
||||
if not valid then
|
||||
return 'InvalidLuaObject'
|
||||
else
|
||||
return get_lua_object_type_safe(object) or 'NoHelpLuaObject'
|
||||
end
|
||||
end
|
||||
|
||||
---Shows the given message if debug is on.
|
||||
---@param position MapPosition
|
||||
---@param message string
|
||||
function Debug.print_position(position, message)
|
||||
Debug.print(format('%s %s', serialize(position), message))
|
||||
end
|
||||
|
||||
---Executes the given callback if cheating is enabled.
|
||||
---@param callback function
|
||||
function Debug.cheat(callback)
|
||||
if _CHEATS then
|
||||
callback()
|
||||
end
|
||||
end
|
||||
|
||||
--- Returns true if the function is a closure, false otherwise.
|
||||
-- A closure is a function that contains 'upvalues' or in other words
|
||||
-- has a reference to a local variable defined outside the function's scope.
|
||||
-- @param func<function>
|
||||
-- @return boolean
|
||||
function Debug.is_closure(func)
|
||||
local i = 1
|
||||
while true do
|
||||
local n = debug_getupvalue(func, i)
|
||||
|
||||
if n == nil then
|
||||
return false
|
||||
elseif n ~= '_ENV' then
|
||||
return true
|
||||
end
|
||||
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
|
||||
return Debug
|
||||
341
exp_legacy/module/overrides/inspect.lua
Normal file
341
exp_legacy/module/overrides/inspect.lua
Normal file
@@ -0,0 +1,341 @@
|
||||
local inspect ={
|
||||
_VERSION = 'inspect.lua 3.1.0',
|
||||
_URL = 'http://github.com/kikito/inspect.lua',
|
||||
_DESCRIPTION = 'human-readable representations of tables',
|
||||
_LICENSE = [[
|
||||
MIT LICENSE
|
||||
|
||||
Copyright (c) 2013 Enrique García Cota
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included
|
||||
in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
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})
|
||||
|
||||
-- Apostrophizes the string if it has quotes, but not aphostrophes
|
||||
-- Otherwise, it returns a regular quoted string
|
||||
local function smartQuote(str)
|
||||
if str:match('"') and not str:match("'") then
|
||||
return "'" .. str .. "'"
|
||||
end
|
||||
return '"' .. str:gsub('"', '\\"') .. '"'
|
||||
end
|
||||
|
||||
-- \a => '\\a', \0 => '\\0', 31 => '\31'
|
||||
local shortControlCharEscapes = {
|
||||
["\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
|
||||
local ch = string.char(i)
|
||||
if not shortControlCharEscapes[ch] then
|
||||
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))
|
||||
end
|
||||
|
||||
local function isIdentifier(str)
|
||||
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
|
||||
end
|
||||
|
||||
local defaultTypeOrders = {
|
||||
['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
|
||||
|
||||
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
|
||||
end
|
||||
|
||||
-- custom types are sorted out alphabetically
|
||||
return ta < tb
|
||||
end
|
||||
|
||||
-- For implementation reasons, the behavior of rawlen & # is "undefined" when
|
||||
-- tables aren't pure sequences. So we implement our own # operator.
|
||||
local function getSequenceLength(t)
|
||||
local len = 1
|
||||
local v = rawget(t, len)
|
||||
while v ~= nil do
|
||||
len = len + 1
|
||||
v = rawget(t, len)
|
||||
end
|
||||
return len - 1
|
||||
end
|
||||
|
||||
local function getNonSequentialKeys(t)
|
||||
local keys = {}
|
||||
local sequenceLength = getSequenceLength(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 str, ok
|
||||
if type(__tostring) == 'function' then
|
||||
ok, str = pcall(__tostring, t)
|
||||
str = ok and str or 'error: ' .. tostring(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 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
|
||||
end
|
||||
end
|
||||
|
||||
return tableAppearances
|
||||
end
|
||||
|
||||
local copySequence = function(s)
|
||||
local copy, len = {}, #s
|
||||
for i=1, len do copy[i] = s[i] end
|
||||
return copy, len
|
||||
end
|
||||
|
||||
local function makePath(path, ...)
|
||||
local keys = {...}
|
||||
local newPath, len = copySequence(path)
|
||||
for i=1, #keys do
|
||||
newPath[len + i] = keys[i]
|
||||
end
|
||||
return newPath
|
||||
end
|
||||
|
||||
local function processRecursive(process, item, path, visited)
|
||||
|
||||
if item == nil then return nil end
|
||||
if visited[item] then return visited[item] end
|
||||
|
||||
local processed = process(item, path)
|
||||
if type(processed) == 'table' 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)
|
||||
if processedKey ~= nil then
|
||||
processedCopy[processedKey] = processRecursive(process, v, makePath(path, processedKey), visited)
|
||||
end
|
||||
end
|
||||
|
||||
local mt = processRecursive(process, getmetatable(processed), makePath(path, inspect.METATABLE), visited)
|
||||
setmetatable(processedCopy, mt)
|
||||
processed = processedCopy
|
||||
end
|
||||
return processed
|
||||
end
|
||||
|
||||
|
||||
|
||||
-------------------------------------------------------------------
|
||||
|
||||
local Inspector = {}
|
||||
local Inspector_mt = {__index = Inspector}
|
||||
|
||||
function Inspector:puts(...)
|
||||
local args = {...}
|
||||
local buffer = self.buffer
|
||||
local len = #buffer
|
||||
for i=1, #args do
|
||||
len = len + 1
|
||||
buffer[len] = args[i]
|
||||
end
|
||||
end
|
||||
|
||||
function Inspector:down(f)
|
||||
self.level = self.level + 1
|
||||
f()
|
||||
self.level = self.level - 1
|
||||
end
|
||||
|
||||
function Inspector:tabify()
|
||||
self:puts(self.newline, string.rep(self.indent, self.level))
|
||||
end
|
||||
|
||||
function Inspector:alreadyVisited(v)
|
||||
return self.ids[v] ~= nil
|
||||
end
|
||||
|
||||
function Inspector:getId(v)
|
||||
local id = self.ids[v]
|
||||
if not id then
|
||||
local tv = type(v)
|
||||
id = (self.maxIds[tv] or 0) + 1
|
||||
self.maxIds[tv] = id
|
||||
self.ids[v] = id
|
||||
end
|
||||
return tostring(id)
|
||||
end
|
||||
|
||||
function Inspector:putKey(k)
|
||||
if isIdentifier(k) then return self:puts(k) end
|
||||
self:puts("[")
|
||||
self:putValue(k)
|
||||
self:puts("]")
|
||||
end
|
||||
|
||||
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), '>')
|
||||
elseif self.level >= self.depth then
|
||||
self:puts('{...}')
|
||||
else
|
||||
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)
|
||||
|
||||
self:puts('{')
|
||||
self:down(function()
|
||||
if toStringResult then
|
||||
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(' ')
|
||||
self:putValue(t[i])
|
||||
count = count + 1
|
||||
end
|
||||
|
||||
for _, k in ipairs(nonSequentialKeys) do
|
||||
if count > 0 then self:puts(', ') end
|
||||
self:tabify()
|
||||
self:putKey(k)
|
||||
self:puts(' = ')
|
||||
self:putValue(t[k])
|
||||
count = count + 1
|
||||
end
|
||||
|
||||
if mt then
|
||||
if count > 0 then self:puts(', ') end
|
||||
self:tabify()
|
||||
self:puts('<metatable> = ')
|
||||
self:putValue(mt)
|
||||
end
|
||||
end)
|
||||
|
||||
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(' ')
|
||||
end
|
||||
|
||||
self:puts('}')
|
||||
end
|
||||
end
|
||||
|
||||
function Inspector:putValue(v)
|
||||
local tv = type(v)
|
||||
|
||||
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
|
||||
self:puts(tostring(v))
|
||||
elseif tv == 'table' then
|
||||
self:putTable(v)
|
||||
else
|
||||
self:puts('<', tv, ' ', self:getId(v), '>')
|
||||
end
|
||||
end
|
||||
|
||||
-------------------------------------------------------------------
|
||||
|
||||
function inspect.inspect(root, options)
|
||||
options = options 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
|
||||
root = processRecursive(process, root, {}, {})
|
||||
end
|
||||
|
||||
local inspector = setmetatable({
|
||||
depth = depth,
|
||||
level = 0,
|
||||
buffer = {},
|
||||
ids = {},
|
||||
maxIds = {},
|
||||
newline = newline,
|
||||
indent = indent,
|
||||
tableAppearances = countTableAppearances(root)
|
||||
}, Inspector_mt)
|
||||
|
||||
inspector:putValue(root)
|
||||
|
||||
return table.concat(inspector.buffer)
|
||||
end
|
||||
|
||||
setmetatable(inspect, { __call = function(_, ...) return inspect.inspect(...) end })
|
||||
|
||||
return inspect
|
||||
55
exp_legacy/module/overrides/math.lua
Normal file
55
exp_legacy/module/overrides/math.lua
Normal file
@@ -0,0 +1,55 @@
|
||||
--luacheck:ignore global math
|
||||
local _sin = math.sin
|
||||
local _cos = math.cos
|
||||
|
||||
math.sqrt2 = math.sqrt(2)
|
||||
math.inv_sqrt2 = 1 / math.sqrt2
|
||||
math.tau = 2 * math.pi
|
||||
|
||||
math.sin = function(x)
|
||||
return math.floor(_sin(x) * 10000000 + 0.5) / 10000000
|
||||
end
|
||||
|
||||
math.cos = function(x)
|
||||
return math.floor(_cos(x) * 10000000 + 0.5) / 10000000
|
||||
end
|
||||
|
||||
-- rounds number (num) to certain number of decimal places (idp)
|
||||
math.round = function(num, idp)
|
||||
local mult = 10 ^ (idp or 0)
|
||||
return math.floor(num * mult + 0.5) / mult
|
||||
end
|
||||
|
||||
math.clamp = function(num, min, max)
|
||||
if num < min then
|
||||
return min
|
||||
elseif num > max then
|
||||
return max
|
||||
else
|
||||
return num
|
||||
end
|
||||
end
|
||||
|
||||
--- Takes two points and calculates the slope of a line
|
||||
-- @param x1, y1 numbers - coordinates of a point on a line
|
||||
-- @param x2, y2 numbers - coordinates of a point on a line
|
||||
-- @return number - the slope of the line
|
||||
math.calculate_slope = function(x1, y1, x2, y2)
|
||||
return math.abs((y2 - y1) / (x2 - x1))
|
||||
end
|
||||
|
||||
--- Calculates the y-intercept of a line
|
||||
-- @param x number - coordinates of point on line
|
||||
-- @param y number - coordinates of point on line
|
||||
-- @param slope number - the slope of a line
|
||||
-- @return number - the y-intercept of a line
|
||||
math.calculate_y_intercept = function(x, y, slope)
|
||||
return y - (slope * x)
|
||||
end
|
||||
|
||||
local deg_to_rad = math.tau / 360
|
||||
math.degrees = function(angle)
|
||||
return angle * deg_to_rad
|
||||
end
|
||||
|
||||
return math
|
||||
10
exp_legacy/module/overrides/print.lua
Normal file
10
exp_legacy/module/overrides/print.lua
Normal file
@@ -0,0 +1,10 @@
|
||||
--luacheck:ignore global print
|
||||
local locale_string = {'', '[PRINT] ', nil}
|
||||
local raw_print = print
|
||||
|
||||
function print(str)
|
||||
locale_string[3] = str
|
||||
log(locale_string)
|
||||
end
|
||||
|
||||
return raw_print
|
||||
8
exp_legacy/module/overrides/require.lua
Normal file
8
exp_legacy/module/overrides/require.lua
Normal file
@@ -0,0 +1,8 @@
|
||||
local loaded = package.loaded
|
||||
local raw_require = require
|
||||
|
||||
function require(path)
|
||||
return loaded[path] or error('Can only require files at runtime that have been required in the control stage.', 2)
|
||||
end
|
||||
|
||||
return raw_require
|
||||
14
exp_legacy/module/overrides/stages.lua
Normal file
14
exp_legacy/module/overrides/stages.lua
Normal file
@@ -0,0 +1,14 @@
|
||||
-- Info on the data lifecycle and how we use it: https://github.com/Refactorio/RedMew/wiki/The-data-lifecycle
|
||||
-- Non-applicable stages are commented out.
|
||||
_STAGE = {
|
||||
--settings = 1,
|
||||
--data = 2,
|
||||
--migration = 3,
|
||||
control = 4,
|
||||
init = 5,
|
||||
load = 6,
|
||||
--config_change = 7,
|
||||
runtime = 8
|
||||
}
|
||||
|
||||
_LIFECYCLE = _STAGE.control
|
||||
437
exp_legacy/module/overrides/table.lua
Normal file
437
exp_legacy/module/overrides/table.lua
Normal file
@@ -0,0 +1,437 @@
|
||||
--luacheck:ignore global table
|
||||
local random = math.random
|
||||
local floor = math.floor
|
||||
local remove = table.remove
|
||||
local tonumber = tonumber
|
||||
local pairs = pairs
|
||||
local table_size = table_size
|
||||
|
||||
--- Searches a table to remove a specific element without an index
|
||||
-- @param t <table> to search
|
||||
-- @param <any> table element to search for
|
||||
function table.remove_element(t, element)
|
||||
for k, v in pairs(t) do
|
||||
if v == element then
|
||||
remove(t, k)
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Removes an item from an array in O(1) time.
|
||||
-- The catch is that fast_remove doesn't guarantee to maintain the order of items in the array.
|
||||
-- @param tbl <table> arrayed table
|
||||
-- @param index <number> Must be >= 0. The case where index > #tbl is handled.
|
||||
function table.remove_index(tbl, index)
|
||||
local count = #tbl
|
||||
if index > count then
|
||||
return
|
||||
elseif index < count then
|
||||
tbl[index] = tbl[count]
|
||||
end
|
||||
|
||||
tbl[count] = nil
|
||||
end
|
||||
|
||||
--- Adds the contents of table t2 to table t1
|
||||
-- @param t1 <table> to insert into
|
||||
-- @param t2 <table> to insert from
|
||||
function table.merge_table(t1, t2)
|
||||
for k, v in pairs(t2) do
|
||||
if tonumber(k) then
|
||||
t1[#t1 + 1] = v
|
||||
else
|
||||
t1[k] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--[[-- Much faster method for inserting items into an array
|
||||
@tparam table tbl the table that will have the values added to it
|
||||
@tparam[opt] number start_index the index at which values will be added, nil means end of the array
|
||||
@tparam table values the new values that will be added to the table
|
||||
@treturn table the table that was passed as the first argument
|
||||
@usage-- Adding 1000 values into the middle of the array
|
||||
local tbl = {}
|
||||
local values = {}
|
||||
for i = 1, 1000 do tbl[i] = i values[i] = i end
|
||||
table.array_insert(tbl, 500, values) -- around 0.4ms
|
||||
]]
|
||||
function table.array_insert(tbl, start_index, values)
|
||||
if not values then
|
||||
values = start_index
|
||||
start_index = nil
|
||||
end
|
||||
|
||||
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]
|
||||
end
|
||||
start_index = start_index-1
|
||||
else
|
||||
start_index = #tbl
|
||||
end
|
||||
|
||||
for offset, item in ipairs(values) do
|
||||
tbl[start_index+offset] = item
|
||||
end
|
||||
|
||||
return tbl
|
||||
end
|
||||
|
||||
--[[-- Much faster method for inserting keys into a table
|
||||
@tparam table tbl the table that will have keys added to it
|
||||
@tparam[opt] number start_index the index at which values will be added, nil means end of the array, numbered indexs only
|
||||
@tparam table tbl2 the table that may contain both string and numbered keys
|
||||
@treturn table the table passed as the first argument
|
||||
@usage-- Merging two tables
|
||||
local tbl = {}
|
||||
local tbl2 = {}
|
||||
for i = 1, 100 do tbl[i] = i tbl['_'..i] = i tbl2[i] = i tbl2['__'..i] = i end
|
||||
table.table_insert(tbl, 50, tbl2)
|
||||
]]
|
||||
function table.table_insert(tbl, start_index, tbl2)
|
||||
if not tbl2 then
|
||||
tbl2 = start_index
|
||||
start_index = nil
|
||||
end
|
||||
|
||||
table.array_insert(tbl, start_index, tbl2)
|
||||
for key, value in pairs(tbl2) do
|
||||
if not tonumber(key) then
|
||||
tbl[key] = value
|
||||
end
|
||||
end
|
||||
|
||||
return tbl
|
||||
end
|
||||
|
||||
--- Checks if a table contains an element
|
||||
-- @param t <table>
|
||||
-- @param e <any> table element
|
||||
-- @return <any> the index of the element or nil
|
||||
function table.get_key(t, e)
|
||||
for k, v in pairs(t) do
|
||||
if v == e then
|
||||
return k
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
--- Checks if the arrayed portion of a table contains an element
|
||||
-- @param t <table>
|
||||
-- @param e <any> table element
|
||||
-- @return <number|nil> the index of the element or nil
|
||||
function table.get_index(t, e)
|
||||
for i = 1, #t do
|
||||
if t[i] == e then
|
||||
return i
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
--- Checks if a table contains an element
|
||||
-- @param t <table>
|
||||
-- @param e <any> table element
|
||||
-- @return <boolean> indicating success
|
||||
function table.contains(t, e)
|
||||
return table.get_key(t, e) and true or false
|
||||
end
|
||||
|
||||
--- Checks if the arrayed portion of a table contains an element
|
||||
-- @param t <table>
|
||||
-- @param e <any> table element
|
||||
-- @return <boolean> indicating success
|
||||
function table.array_contains(t, e)
|
||||
return table.get_index(t, e) and true or false
|
||||
end
|
||||
|
||||
--- Extracts certain keys from a table
|
||||
-- @usage local key_three, key_one = extract({key_one='foo', key_two='bar', key_three=true}, 'key_three', 'key_one')
|
||||
-- @tparam table tbl table the which contains the keys
|
||||
-- @tparam string ... the names of the keys you want extracted
|
||||
-- @return the keys in the order given
|
||||
function table.extract_keys(tbl, ...)
|
||||
local values = {}
|
||||
for _, key in pairs({...}) do
|
||||
table.insert(values, tbl[key])
|
||||
end
|
||||
return table.unpack(values)
|
||||
end
|
||||
|
||||
--- Adds an element into a specific index position while shuffling the rest down
|
||||
-- @param t <table> to add into
|
||||
-- @param index <number> the position in the table to add to
|
||||
-- @param element <any> to add to the table
|
||||
function table.set(t, index, element)
|
||||
local i = 1
|
||||
for k in pairs(t) do
|
||||
if i == index then
|
||||
t[k] = element
|
||||
return nil
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
error('Index out of bounds', 2)
|
||||
end
|
||||
|
||||
--- Chooses a random entry from a table
|
||||
-- because this uses math.random, it cannot be used outside of events
|
||||
-- @param t <table>
|
||||
-- @param key <boolean> to indicate whether to return the key or value
|
||||
-- @return <any> a random element of table t
|
||||
function table.get_random_dictionary_entry(t, key)
|
||||
local target_index = random(1, table_size(t))
|
||||
local count = 1
|
||||
for k, v in pairs(t) do
|
||||
if target_index == count then
|
||||
if key then
|
||||
return k
|
||||
else
|
||||
return v
|
||||
end
|
||||
end
|
||||
count = count + 1
|
||||
end
|
||||
end
|
||||
|
||||
--- Chooses a random entry from a weighted table
|
||||
-- because this uses math.random, it cannot be used outside of events
|
||||
-- @param weighted_table <table> of tables with items and their weights
|
||||
-- @param item_index <number> of the index of items, defaults to 1
|
||||
-- @param weight_index <number> of the index of the weights, defaults to 2
|
||||
-- @return <any> table element
|
||||
function table.get_random_weighted(weighted_table, item_index, weight_index)
|
||||
local total_weight = 0
|
||||
item_index = item_index or 1
|
||||
weight_index = weight_index or 2
|
||||
|
||||
for _, w in pairs(weighted_table) do
|
||||
total_weight = total_weight + w[weight_index]
|
||||
end
|
||||
|
||||
local index = random() * total_weight
|
||||
local weight_sum = 0
|
||||
for _, w in pairs(weighted_table) do
|
||||
weight_sum = weight_sum + w[weight_index]
|
||||
if weight_sum >= index then
|
||||
return w[item_index]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Clears all existing entries in a table
|
||||
-- @param t <table> to clear
|
||||
-- @param array <boolean> to indicate whether the table is an array or not
|
||||
function table.clear_table(t, array)
|
||||
if array then
|
||||
for i = 1, #t do
|
||||
t[i] = nil
|
||||
end
|
||||
else
|
||||
for i in pairs(t) do
|
||||
t[i] = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Creates a fisher-yates shuffle of a sequential number-indexed table
|
||||
-- because this uses math.random, it cannot be used outside of events if no rng is supplied
|
||||
-- from: http://www.sdknews.com/cross-platform/corona/tutorial-how-to-shuffle-table-items
|
||||
-- @param t <table> to shuffle
|
||||
-- @param rng <function> to provide random numbers
|
||||
function table.shuffle_table(t, rng)
|
||||
local rand = rng or math.random
|
||||
local iterations = #t
|
||||
if iterations == 0 then
|
||||
error('Not a sequential table')
|
||||
return
|
||||
end
|
||||
local j
|
||||
|
||||
for i = iterations, 2, -1 do
|
||||
j = rand(i)
|
||||
t[i], t[j] = t[j], t[i]
|
||||
end
|
||||
end
|
||||
|
||||
--- Default table comparator sort function.
|
||||
-- @local
|
||||
-- @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 tx = type(x)
|
||||
local ty = type(y)
|
||||
if tx == ty 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
|
||||
else
|
||||
return false --only y is a number and goes first
|
||||
end
|
||||
end
|
||||
|
||||
--- Returns a copy of all of the values in the table.
|
||||
-- @tparam table tbl the to copy the keys from, or an empty table if tbl is nil
|
||||
-- @tparam[opt] boolean sorted whether to sort the keys (slower) or keep the random order from pairs()
|
||||
-- @tparam[opt] boolean as_string whether to try and parse the values as strings, or leave them as their existing type
|
||||
-- @treturn array an array with a copy of all the values in the table
|
||||
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
|
||||
for _, v in pairs(tbl) do
|
||||
n = n + 1
|
||||
valueset[n] = tostring(v)
|
||||
end
|
||||
else
|
||||
for _, v in pairs(tbl) do
|
||||
n = n + 1
|
||||
valueset[n] = v
|
||||
end
|
||||
end
|
||||
if sorted then
|
||||
table.sort(valueset, sortFunc)
|
||||
end
|
||||
return valueset
|
||||
end
|
||||
|
||||
--- Returns a copy of all of the keys in the table.
|
||||
-- @tparam table tbl the to copy the keys from, or an empty table if tbl is nil
|
||||
-- @tparam[opt] boolean sorted whether to sort the keys (slower) or keep the random order from pairs()
|
||||
-- @tparam[opt] boolean as_string whether to try and parse the keys as strings, or leave them as their existing type
|
||||
-- @treturn array an array with a copy of all the keys in the table
|
||||
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
|
||||
for k, _ in pairs(tbl) do
|
||||
n = n + 1
|
||||
keyset[n] = tostring(k)
|
||||
end
|
||||
else
|
||||
for k, _ in pairs(tbl) do
|
||||
n = n + 1
|
||||
keyset[n] = k
|
||||
end
|
||||
end
|
||||
if sorted then
|
||||
table.sort(keyset, sortFunc)
|
||||
end
|
||||
return keyset
|
||||
end
|
||||
|
||||
--- Returns the list is a sorted way that would be expected by people (this is by key)
|
||||
-- @tparam table tbl the table to be sorted
|
||||
-- @treturn table the sorted table
|
||||
function table.alphanumsort(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
|
||||
table.sort(o, function(a, b)
|
||||
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
|
||||
|
||||
--- Returns the list is a sorted way that would be expected by people (this is by key) (faster alternative than above)
|
||||
-- @tparam table tbl the table to be sorted
|
||||
-- @treturn table the sorted table
|
||||
function table.keysort(tbl)
|
||||
local o = table.get_keys(tbl, true)
|
||||
local _tbl = {}
|
||||
for _, k in pairs(o) do _tbl[k] = tbl[k] end
|
||||
return _tbl
|
||||
end
|
||||
|
||||
--[[
|
||||
Returns the index where t[index] == target.
|
||||
If there is no such index, returns a negative value such that bit32.bnot(value) is
|
||||
the index that the value should be inserted to keep the list ordered.
|
||||
t must be a list in ascending order for the return value to be valid.
|
||||
|
||||
Usage example:
|
||||
local t = {1, 3,5, 7,9}
|
||||
local x = 5
|
||||
local index = table.binary_search(t, x)
|
||||
if index < 0 then
|
||||
game.print("value not found, smallest index where t[index] > x is: " .. bit32.bnot(index))
|
||||
else
|
||||
game.print("value found at index: " .. index)
|
||||
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.
|
||||
|
||||
local lower = 1
|
||||
local upper = #t
|
||||
|
||||
if upper == 0 then
|
||||
return -2 -- ~1
|
||||
end
|
||||
|
||||
repeat
|
||||
local mid = floor((lower + upper) * 0.5)
|
||||
local value = t[mid]
|
||||
if value == target then
|
||||
return mid
|
||||
elseif value < target then
|
||||
lower = mid + 1
|
||||
else
|
||||
upper = mid - 1
|
||||
end
|
||||
until lower > upper
|
||||
|
||||
return -1 - lower -- ~lower
|
||||
end
|
||||
|
||||
-- add table-related functions that exist in base factorio/util to the 'table' table
|
||||
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.
|
||||
-- @param table <table> the table to serialize
|
||||
-- @param options <table> options are depth, newline, indent, process
|
||||
-- depth sets the maximum depth that will be printed out. When the max depth is reached, inspect will stop parsing tables and just return {...}
|
||||
-- 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 'overrides.inspect' --- @dep overrides.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
|
||||
|
||||
--- Creates a deepcopy of a table. Metatables and LuaObjects inside the table are shallow copies.
|
||||
-- Shallow copies meaning it copies the reference to the object instead of the object itself.
|
||||
-- @param object <table> the object to copy
|
||||
-- @return <table> the copied object
|
||||
table.deep_copy = table.deepcopy
|
||||
|
||||
--- Merges multiple tables. Tables later in the list will overwrite entries from tables earlier in the list.
|
||||
-- Ex. merge({{1, 2, 3}, {[2] = 0}, {[3] = 0}}) will return {1, 0, 0}
|
||||
-- @param tables <table> takes a table of tables to merge
|
||||
-- @return <table> a merged table
|
||||
table.merge = util.merge
|
||||
|
||||
--- Determines if two tables are structurally equal.
|
||||
-- Notice: tables that are LuaObjects or contain LuaObjects won't be compared correctly, use == operator for LuaObjects
|
||||
-- @param tbl1 <table>
|
||||
-- @param tbl2 <table>
|
||||
-- @return <boolean>
|
||||
table.equals = table.compare
|
||||
|
||||
return table
|
||||
5
exp_legacy/module/overrides/version.lua
Normal file
5
exp_legacy/module/overrides/version.lua
Normal file
@@ -0,0 +1,5 @@
|
||||
return {
|
||||
expgaming_lua = '6.2.0',
|
||||
expgaming_api = '2.0.0',
|
||||
redmew_lua = '2019-02-24-76871ee'
|
||||
}
|
||||
Reference in New Issue
Block a user