From 886b764543ad3a223cf5b5749974fb530ba83023 Mon Sep 17 00:00:00 2001 From: Simon Brodtmann Date: Mon, 6 Jan 2025 12:46:16 +0100 Subject: [PATCH] Add util/table --- cf-lib/util.lua | 1 + cf-lib/util/table.lua | 67 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 cf-lib/util.lua create mode 100644 cf-lib/util/table.lua diff --git a/cf-lib/util.lua b/cf-lib/util.lua new file mode 100644 index 0000000..281a96e --- /dev/null +++ b/cf-lib/util.lua @@ -0,0 +1 @@ +require("util/table") \ No newline at end of file diff --git a/cf-lib/util/table.lua b/cf-lib/util/table.lua new file mode 100644 index 0000000..c6a5f13 --- /dev/null +++ b/cf-lib/util/table.lua @@ -0,0 +1,67 @@ +local meld = require("__core__/lualib/meld") + +--- Checks if a table contains a certain value. +--- @param table table The table to check +--- @param value any The value to check for +--- @return boolean +function table.contains(table, value) + for _, v in pairs(table) do + if v == value then + return true + end + end + return false +end + +--- Assigns all values from source to target without a deep merge. +--- @param target table The table to assign to +--- @param source table The table to assign from +--- @return table The target table +function table.assign(target, source) + for k, v in pairs(source) do + if type(k) == "number" then + if (v ~= nil) then + table.insert(target, v) + end + else + target[k] = v + end + end + return target +end + +--- Deeply merges two tables together, with the source table overwriting the target table. +--- @param target table The table to merge into +--- @param source table The table to merge from +--- @return table The target table +function table.merge(target, source) + meld(target, source) + return target +end + +--- Removes a value from a table. +--- @param target table The table to remove from +--- @param value any The value to remove +--- @return table The target table +table.removeValue = function(target, value) + for i, v in ipairs(target) do + if v == value then + target.remove(target, i) + return target + end + end +end + +--- Filters a table based on a predicate function. +--- When the predicate returns true, the value is kept in the table. +--- @param target table The table to filter +--- @param predicate fun(value: any, key: any): boolean The predicate function +function table.filter(target, predicate) + local result = {} + for k, v in pairs(target) do + if predicate(v, k) then + result[k] = v + end + end + return result +end \ No newline at end of file