a bit more progress on lua bindings
[philodendron.git] / sketches / pp.lua
blob017721bcbaa5853ceb095958f075dd48da2c9dcd
2 require "data_structures"
4 function serialize(o, maxdepth, indent, s)
5 local seen = s or Stack:new()
6 local t = type(o)
7 local new_max_depth
8 if maxdepth then new_max_depth = maxdepth-1 end
9 if new_max_depth == 0 then return "<too deep>" end
11 if t == "table" and seen:contains(o) then
12 return "..."
13 else
14 seen:push(o)
15 end
17 if indent and type(indent) ~= "string" then
18 indent = ""
19 end
21 local result
23 if t == "string" then
24 result = string.format("%q", o)
25 elseif t == "table" and o.__index == o then
26 result = string.format("Class: %q", o.name)
27 elseif t == "table" and not (o.class and o.class.__tostring) then
28 local nestedIndent
29 if indent then
30 nestedIndent = indent .. " "
31 end
33 result = "{"
34 if nestedIndent then result = result .. "\n" .. nestedIndent end
35 local nextIndex = 1
36 local first = true
37 for k, v in pairs(o) do
38 if first then
39 first = false
40 else
41 result = result .. ", "
42 if nestedIndent then result = result .. "\n" .. nestedIndent end
43 end
44 if type(k) == "number" and k == nextIndex then
45 nextIndex = nextIndex + 1
46 else
47 if type(k) == "string" and string.find(k, "^[_%a][_%w]*$") then
48 result = result .. k
49 else
50 result = result .. "[" .. serialize(k, new_max_depth, nil, seen) .. "]"
51 end
52 result = result .. " = "
53 end
54 result = result .. serialize(v, new_max_depth, nestedIndent, seen)
55 end
56 if indent then
57 result = result .. "\n" .. indent
58 end
59 result = result .. "}"
60 else
61 result = tostring(o)
62 end
64 seen:pop()
65 return result
66 end