Warning: this is an htmlized version!
The original is here, and the conversion rules are here. |
-- This file: -- http://anggtwu.net/LUA/tos2.lua.html -- http://anggtwu.net/LUA/tos2.lua -- (find-angg "LUA/tos2.lua") -- Author: Eduardo Ochs <eduardoochs@gmail.com> -- -- My is one of my oldest implementations of a "tostring" for Lua that -- could pretty-print tables. Note the "tos_images" and the "tos_keys"! -- Based on: (find-angg "LUA/tos.lua") -- See also: (find-angg "LUA/lua50init.lua" "Tos") -- (find-angg "LUA/lua50init.lua" "mytostring") -- (find-dn5 "tos.lua") -- -- (defun e () (interactive) (find-angg "LUA/tos2.lua")) tos = function (o) tos_images = {}; return tos_image(o) end tos_images = {} tos_image = function (o) if tos_images[o] then return tos_images[o] end if o == nil then return "nil" end tos_images[o] = tos_calc(o) return tos_images[o] end tos_calc = function (o) local t = type(o) if t == "number" then return tos_number(o) end if t == "string" then return tos_string(o) end if t == "table" then return tos_table(o) end if t == "nil" or t == "boolean" then return tostring(o) end return tos_other(o) end tos_number = function (n) return tostring(n) end tos_string = function (s) return string.format("%q", s) end tos_other = function (o) return "<"..tostring(o)..">" end tos_table = function (tbl) return "{"..tos_table_body(tbl).."}" end tos_table_body = function (tbl, sep) local keys = tos_keys(tbl) local images = {} for _,key in ipairs(keys) do table.insert(images, tos_key_value_pair(key, tbl[key])) end return table.concat(images, sep or ", ") end tos_key_value_pair = function (k, v) return tos_image(k).."="..tos_image(v) end tos_compare = function (o1, o2) return tos_image(o1) < tos_timage(o2) end tos_keys = function (tbl) local keys = {number={}, string={}, table={}, other={}} for key,_ in pairs(tbl) do table.insert(keys[type(key)] or keys.other, key) end table.sort(keys.number) table.sort(keys.string) table.sort(keys.table, tos_compare) table.sort(keys.other, tos_compare) local allkeys = {} for _,k in ipairs(keys.number) do table.insert(allkeys, k) end for _,k in ipairs(keys.string) do table.insert(allkeys, k) end for _,k in ipairs(keys.table) do table.insert(allkeys, k) end for _,k in ipairs(keys.other) do table.insert(allkeys, k) end return allkeys end tos_arg = function (arg, sep) local images = map(tos, arg, arg.n) return table.concat(images, sep or " ") end --[[ * (eepitch-lua51) * (eepitch-kill) * (eepitch-lua51) ee_dofile "~/LUA/tos2.lua" = tos{} = tos{a="aa", 22} = tos({{"a", b="bb", 22}, {}, print}) --]]