diff options
-rw-r--r-- | Data/BuiltIn/Libraries/GameLab/Utils/init.lua | 93 |
1 files changed, 76 insertions, 17 deletions
diff --git a/Data/BuiltIn/Libraries/GameLab/Utils/init.lua b/Data/BuiltIn/Libraries/GameLab/Utils/init.lua index 86bf90e..53188fa 100644 --- a/Data/BuiltIn/Libraries/GameLab/Utils/init.lua +++ b/Data/BuiltIn/Libraries/GameLab/Utils/init.lua @@ -1,26 +1,85 @@ local utils = GameLab.Package("GameLab.Utils")
-utils.Clone = function(obj)
- local lut = {}
-
- local function copy(object)
- if type(object) ~= "table" then
+function utils.Deepcopy(object)
+ local lookup_table = {}
+ local function _copy(object)
+ if type(object) ~= "table" then
return object
- elseif lut[object] then
- return lut[object]
- end
+ elseif lookup_table[object] then
+ return lookup_table[object]
+ end
+ local new_table = {}
+ lookup_table[object] = new_table
+ for index, value in pairs(object) do
+ new_table[_copy(index)] = _copy(value)
+ end
+ return setmetatable(new_table, getmetatable(object))
+ end
+ return _copy(object)
+end
+
+function utils.RunInEnvironment(fn, fnenv)
+ setfenv(fn, fnenv)
+ return xpcall(fn, debug.traceback)
+end
+
+function utils.Reduce(tbl, filterfn)
+ local res = {}
+ for k,v in pairs(tbl) do
+ if filterfn(k,v) then
+ res[k] = v
+ end
+ end
+ return tbl
+end
- local newtable = {}
- lut[object] = newtable
+-- concatenate two array-style tables
+function utils.JoinArrays(...)
+ local ret = {}
+ for i,array in ipairs({...}) do
+ for j,val in ipairs(array) do
+ table.insert(ret, val)
+ end
+ end
+ return ret
+end
- for k, v in pairs(object) do
- newtable[copy(k)] = copy(value)
- end
+-- merge two array-style tables, only allowing each value once
+function utils.ArrayUnion(...)
+ local ret = {}
+ for i,array in ipairs({...}) do
+ for j,val in ipairs(array) do
+ if not table.contains(ret, val) then
+ table.insert(ret, val)
+ end
+ end
+ end
+ return ret
+end
- return setmetatable(newtable, getmetatable(object))
- end
+-- merge two map-style tables, overwriting duplicate keys with the latter map's value
+function utils.MergeMaps(...)
+ local ret = {}
+ for i,map in ipairs({...}) do
+ for k,v in pairs(map) do
+ ret[k] = v
+ end
+ end
+ return ret
+end
- return copy(obj)
-end
+-- Adds 'addition' to the end of 'orig', 'mult' times.
+-- ExtendedArray({"one"}, {"two","three"}, 2) == {"one", "two", "three", "two", "three" }
+function utils.ExtendedArray(orig, addition, mult)
+ local ret = {}
+ for k,v in pairs(orig) do
+ ret[k] = v
+ end
+ mult = mult or 1
+ for i=1,mult do
+ table.insert(ret,addition)
+ end
+ return ret
+end
return utils
\ No newline at end of file |