diff --git a/mods/CORE/mcl_util/init.lua b/mods/CORE/mcl_util/init.lua index 6b3bd6db1..22b0c2ce3 100644 --- a/mods/CORE/mcl_util/init.lua +++ b/mods/CORE/mcl_util/init.lua @@ -3,52 +3,7 @@ mcl_util = {} local modname = minetest.get_current_modname() local modpath = minetest.get_modpath(modname) dofile(modpath.."/roman_numerals.lua") - --- Updates all values in t using values from to*. -function table.update(t, ...) - for _, to in ipairs {...} do - for k, v in pairs(to) do - t[k] = v - end - end - return t -end - --- Updates nil values in t using values from to*. -function table.update_nil(t, ...) - for _, to in ipairs {...} do - for k, v in pairs(to) do - if t[k] == nil then - t[k] = v - end - end - end - return t -end - ----Works the same as `pairs`, but order returned by keys ---- ----Taken from https://www.lua.org/pil/19.3.html ----@generic T: table, K, V, C ----@param t T ----@param f? fun(a: C, b: C):boolean ----@return fun():K, V -function table.pairs_by_keys(t, f) - local a = {} - for n in pairs(t) do table.insert(a, n) end - table.sort(a, f) - - local i = 0 -- iterator variable - local function iter() -- iterator function - i = i + 1 - if a[i] == nil then - return nil - else - return a[i], t[a[i]] - end - end - return iter -end +dofile(modpath.."/table.lua") local LOGGING_ON = minetest.settings:get_bool("mcl_logging_default", false) local LOG_MODULE = "[MCL2]" diff --git a/mods/CORE/mcl_util/table.lua b/mods/CORE/mcl_util/table.lua new file mode 100644 index 000000000..5f62b3fcf --- /dev/null +++ b/mods/CORE/mcl_util/table.lua @@ -0,0 +1,67 @@ +-- Updates all values in t using values from to*. +function table.update(t, ...) + for _, to in ipairs {...} do + for k, v in pairs(to) do + t[k] = v + end + end + return t +end + +-- Updates nil values in t using values from to*. +function table.update_nil(t, ...) + for _, to in ipairs {...} do + for k, v in pairs(to) do + if t[k] == nil then + t[k] = v + end + end + end + return t +end + +---Works the same as `pairs`, but order returned by keys +--- +---Taken from https://www.lua.org/pil/19.3.html +---@generic T: table, K, V, C +---@param t T +---@param f? fun(a: C, b: C):boolean +---@return fun():K, V +function table.pairs_by_keys(t, f) + local a = {} + for n in pairs(t) do table.insert(a, n) end + table.sort(a, f) + + local i = 0 -- iterator variable + local function iter() -- iterator function + i = i + 1 + if a[i] == nil then + return nil + else + return a[i], t[a[i]] + end + end + return iter +end + +function table.find(t, item) + for k,v in pairs(t) do + if v == item then return k end + end + return nil +end + +function table.intersect(a, b) + local values_map = {} + + for _,v in pairs(a) do values_map[v] = 1 end + for _,v in pairs(b) do values_map[v] = (values_map[v] or 0) + 1 end + + -- Get all the values that are in both tables + local result = {} + for v,count in pairs(values_map) do + if count == 2 then table.insert(result, v) end + end + return result +end +