From e553b3e38eb2cf68f64800ffbf40e9ea9ecdff01 Mon Sep 17 00:00:00 2001
From: quou <quou@disroot.org>
Date: Fri, 21 Jul 2023 09:20:38 +1000
Subject: Initial commit.

---
 util.lua | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 73 insertions(+)
 create mode 100644 util.lua

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
-- 
cgit v1.2.3-54-g00ecf