summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorquou <quou@disroot.org>2023-07-21 09:20:38 +1000
committerquou <quou@disroot.org>2023-07-21 09:20:38 +1000
commite553b3e38eb2cf68f64800ffbf40e9ea9ecdff01 (patch)
tree33bde8b9bd67e12ec9f506aaf4d7df7afa484599
Initial commit.HEADmaster
-rw-r--r--util.lua73
1 files changed, 73 insertions, 0 deletions
diff --git a/util.lua b/util.lua
new file mode 100644
index 0000000..6cba798
--- /dev/null
+++ b/util.lua
@@ -0,0 +1,73 @@
+-- Some useful Lua functions.
+
+util = {}
+
+function util.key_ordered_pairs(t, f)
+ local a = {}
+ for n in pairs(t) do table.insert(a, n) end
+ table.sort(a, f)
+ local i = 0
+ local iter = function ()
+ i = i + 1
+ if a[i] == nil then return nil
+ else return a[i], t[a[i]]
+ end
+ end
+ return iter
+end
+
+local function write_imp(name, t, file, indent)
+ for i = 1, indent do
+ file:write("\t")
+ end
+ local ty = type(t)
+ if name then
+ file:write(string.format("%s = ", name))
+ end
+ if ty == 'table' then
+ file:write("{\n")
+ local del = false
+ if #t > 0 then
+ for i, v in ipairs(t) do
+ write_imp(nil, v, file, indent + 1)
+ file:write(',\n')
+ end
+ del = true
+ else
+ for k, v in util.key_ordered_pairs(t) do
+ write_imp(tostring(k), v, file, indent + 1)
+ file:write(',\n')
+ del = true
+ end
+ end
+ if del then
+ file:seek('cur', -2) -- Wipe the last comma
+ end
+ file:write('\n')
+ for i = 1, indent do
+ file:write("\t")
+ end
+ file:write("}")
+ elseif ty == 'string' then
+ file:write(string.format("'%s'", t))
+ else
+ file:write(string.format("%s", tostring(t)))
+ end
+end
+
+function util.write_table(kname, t, fname)
+ local file = io.open(fname, 'w')
+ write_imp(kname, t, file, 0)
+end
+
+function util.deep_copy(tab)
+ local r = {}
+ for k, v in pairs(tab) do
+ local nv
+ if type(v) == 'table' then
+ nv = util.deep_copy(v)
+ else nv = v end
+ r[k] = nv
+ end
+ return r
+end