Frédéric Lécaille | 54f2bcf | 2018-08-29 13:46:24 +0200 | [diff] [blame] | 1 | -- Copyright 2016 Thierry Fournier |
| 2 | |
| 3 | function color(index, str) |
| 4 | return "\x1b[" .. index .. "m" .. str .. "\x1b[00m" |
| 5 | end |
| 6 | |
| 7 | function nocolor(index, str) |
| 8 | return str |
| 9 | end |
| 10 | |
| 11 | function sp(count) |
| 12 | local spaces = "" |
| 13 | while count > 0 do |
| 14 | spaces = spaces .. " " |
| 15 | count = count - 1 |
| 16 | end |
| 17 | return spaces |
| 18 | end |
| 19 | |
| 20 | function 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 |
| 32 | end |
| 33 | |
| 34 | function 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 |
| 84 | end |
| 85 | |
| 86 | function 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") |
| 96 | end |