blob: 185614fb2e68faf19b3e9e7523076560904e6712 [file] [log] [blame]
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02001-- Copyright 2016 Thierry Fournier
2
3function color(index, str)
4 return "\x1b[" .. index .. "m" .. str .. "\x1b[00m"
5end
6
7function nocolor(index, str)
8 return str
9end
10
11function sp(count)
12 local spaces = ""
13 while count > 0 do
14 spaces = spaces .. " "
15 count = count - 1
16 end
17 return spaces
18end
19
20function escape(str)
21 local s = ""
22 for i = 1, #str do
23 local c = str:sub(i,i)
24 local ascii = string.byte(c, 1)
25 if ascii > 126 or ascii < 20 then
26 s = s .. string.format("\\x%02x", ascii)
27 else
28 s = s .. c
29 end
30 end
31 return s
32end
33
34function print_rr(p, indent, c, wr, hist)
35 local i = 0
36 local nl = ""
37
38 if type(p) == "table" then
39 wr(c("33", "(table)") .. " " .. c("36", tostring(p)) .. " [")
40
41 for idx, value in ipairs(hist) do
42 if value == p then
43 wr(" " .. c("35", "/* recursion */") .. " ]")
44 return
45 end
46 end
47 hist[indent + 1] = p
48
49 mt = getmetatable(p)
50 if mt ~= nil then
51 wr("\n" .. sp(indent+1) .. c("31", "METATABLE") .. ": ")
52 print_rr(mt, indent+1, c, wr, hist)
53 end
54
55 for k,v in pairs(p) do
56 if i > 0 then
57 nl = "\n"
58 else
59 wr("\n")
60 end
61 wr(nl .. sp(indent+1))
62 if type(k) == "number" then
63 wr(c("32", tostring(k)))
64 else
65 wr("\"" .. c("32", escape(tostring(k))) .. "\"")
66 end
67 wr(": ")
68 print_rr(v, indent+1, c, wr, hist)
69 i = i + 1
70 end
71 if i == 0 then
72 wr(" " .. c("35", "/* empty */") .. " ]")
73 else
74 wr("\n" .. sp(indent) .. "]")
75 end
76
77 hist[indent + 1] = nil
78
79 elseif type(p) == "string" then
80 wr(c("33", "(string)") .. " \"" .. c("36", escape(p)) .. "\"")
81 else
82 wr(c("33", "(" .. type(p) .. ")") .. " " .. c("36", tostring(p)))
83 end
84end
85
86function print_r(p, col, wr)
87 if col == nil then col = true end
88 if wr == nil then wr = function(msg) io.stdout:write(msg) end end
89 local hist = {}
90 if col == true then
91 print_rr(p, 0, color, wr, hist)
92 else
93 print_rr(p, 0, nocolor, wr, hist)
94 end
95 wr("\n")
96end