-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlx.lua
executable file
·81 lines (71 loc) · 2.2 KB
/
lx.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/env lua
-- Copyright © 2025 Mark Summerfield. All rights reserved.
local lx = {}
function lx.fprintf(file, fmt, ...) file:write(string.format(fmt, ...)) end
function lx.printf(fmt, ...) io.stdout:write(string.format(fmt, ...)) end
function lx.sprintf(fmt, ...) return string.format(fmt, ...) end
function lx.typeof(x)
local t = type(x)
if t == "table" then
local ok, name = pcall(x.typeof)
if ok then return name end
elseif t == "number" then
return math.type(x)
end
return t
end
function lx.timeit(name, func)
local t = os.clock()
func()
t = os.clock() - t
lx.printf("%s %9.3f sec\n", name, t)
end
local function maybe_quote(x)
if type(x) == "string" then return lx.sprintf("%q", x) end
return tostring(x)
end
local function dump_tbl(tbl, indent, done)
done = done or {}
indent = indent or 0
if type(tbl) == "table" then
local strs = {}
for key, value in pairs(tbl) do
table.insert(strs, string.rep(" ", indent)) -- indent it
if type(value) == "table" and not done[value] then
done[value] = true
table.insert(strs, key .. " = {\n")
table.insert(strs, dump_tbl(value, indent + 2, done))
table.insert(strs, string.rep(" ", indent)) -- indent it
table.insert(strs, "}\n")
elseif "number" == type(key) then
table.insert(strs, maybe_quote(value) .. "\n")
else
table.insert(
strs,
lx.sprintf(
"%s = %s\n",
maybe_quote(key),
maybe_quote(value)
)
)
end
end
return table.concat(strs)
else
return tbl .. "\n"
end
end
function lx.dump(x)
local kind = lx.typeof(x)
if kind == "List" or kind == "Map" or kind == "Set" then
return x:tostring(true)
elseif kind == "table" then
return dump_tbl(x)
elseif kind == "string" then
return lx.sprintf("%q", x)
elseif kind == "nil" then
return tostring(nil)
end
return tostring(x)
end
return lx