Last active
November 24, 2019 16:41
-
-
Save jakobrs/0d987fc56f9dae3b02ec69216f2c95e8 to your computer and use it in GitHub Desktop.
"serialise" and print Lua values, including tables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local function find(tbl, val) | |
for i, v in ipairs(tbl) do | |
if v == val then | |
return i | |
end | |
end | |
end | |
function serialiseC(out, a, useColours, simplified) | |
local dont = {} | |
if useColours == nil then | |
useColours = true | |
end | |
if simplified == nil then | |
simplified = true | |
end | |
local function serialiseI(a) | |
do | |
local index = find(dont, a) | |
if index then | |
if useColours then | |
out("\27[36m^" .. (#dont - tostring(index) + 1) .. "\27[0m") | |
else | |
out("^" .. (#dont - tostring(index) + 1)) | |
end | |
return | |
--error("Recursive value hit during serialisation (" .. #dont .. ")") | |
end | |
table.insert(dont, a) | |
end | |
local t = type(a) | |
if t == "string" then | |
out(string.format("%q", a)) | |
elseif t == "table" then | |
out "{" | |
local first = true | |
for i, v in ipairs(a) do | |
if first then | |
first = false | |
else | |
out ", " | |
end | |
serialiseI(v) | |
end | |
for k, v in pairs(a) do | |
-- Ignore keys that have already been handled by the above ipairs loop | |
if not (type(k) == "number" and 1 <= k and k <= #a) then | |
if first then | |
first = false | |
else | |
out ", a" | |
end | |
if type(k) == "string" and k:match("^[a-zA-Z_][a-zA-Z_]*$") then | |
out(k) | |
out " = " | |
else | |
out "[" | |
serialiseI(k) | |
out "] = " | |
end | |
serialiseI(v) | |
end | |
end | |
out "}" | |
elseif simplified then | |
if t == "function" then | |
out "<function>" | |
elseif t == "thread" then | |
out "<thread>" | |
elseif t == "userdata" then | |
out "<userdata>" | |
else | |
out(tostring(a)) | |
end | |
else | |
out(tostring(a)) | |
end | |
table.remove(dont) | |
end | |
serialiseI(a) | |
end | |
function serialise(a) | |
local ret = {} | |
local function out(a) | |
table.insert(ret, a) | |
end | |
serialiseC(out, a, false) | |
return table.concat(ret) | |
end | |
function writes(...) | |
local first = true | |
for _, v in ipairs {...} do | |
if not first then | |
io.write "\t" | |
end | |
first = false | |
serialiseC(io.write, v) | |
end | |
end | |
function prints(...) | |
writes(...) | |
print() | |
end | |
serialize, serializeC = serialise, serialiseC |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment