From eb9018777664037e2d367b0040c6b2dce17ef150 Mon Sep 17 00:00:00 2001 From: Dan Ports Date: Sat, 23 Jun 2018 21:35:31 -0400 Subject: [PATCH] #2: Import util package. --- src/util/.manifest | 3 +++ src/util/apis/util | 54 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 src/util/.manifest create mode 100644 src/util/apis/util diff --git a/src/util/.manifest b/src/util/.manifest new file mode 100644 index 0000000..d6456c5 --- /dev/null +++ b/src/util/.manifest @@ -0,0 +1,3 @@ +{ + description = "API with a handful of table-related helper functions" +} \ No newline at end of file diff --git a/src/util/apis/util b/src/util/apis/util new file mode 100644 index 0000000..1112ade --- /dev/null +++ b/src/util/apis/util @@ -0,0 +1,54 @@ +-- The problem is that we call os.loadAPI multiple times, and CC loads and overwrites the API every time. +-- We can either stash API variables in a global table like this or patch CC to load each API once. +function initializeGlobalTable(name) + return getTable(_G, name) +end + +function getCoroutineTable(name) + return getTable(getTable(initializeGlobalTable("coroutineStorage"), coroutine.running()), name) +end + +function getTable(obj, key) + local value = obj[key] + if value == nil then + value = {} + obj[key] = value + end + return value +end + +function getNextUnusedIndex(obj) + local id = 1 + while obj[id] ~= nil do + id = id + 1 + end + return id +end + +function insertRange(obj, items) + for _, item in pairs(items) do + table.insert(obj, item) + end +end + +function removeWhere(obj, test) + local position = 1 + while position <= #obj do + if test(obj[position]) then + table.remove(obj, position) + else + position = position + 1 + end + end +end + +function deepClone(obj) + if type(obj) ~= "table" then + return obj + end + local clone = {} + for k, v in pairs(obj) do + clone[k] = deepClone(v) + end + return clone +end \ No newline at end of file