Last active
June 19, 2022 12:53
-
-
Save nfrid/2b4b62900d68f68d30f4ba82fbeeb02d to your computer and use it in GitHub Desktop.
lua: dump any value as a formatted string
This file contains 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
--- Dump value of a variable in a formatted string | |
-- | |
--- @param o table Dumpable object | |
--- @param tbs string|nil Tabulation string, ' ' by default | |
--- @param tb number|nil Initial tabulation level, 0 by default | |
--- @return string | |
local function dump(o, tbs, tb) | |
tb = tb or 0 | |
tbs = tbs or ' ' | |
if type(o) == 'table' then | |
local s = '{' | |
if (next(o)) then s = s .. '\n' else return s .. '}' end | |
tb = tb + 1 | |
for k,v in pairs(o) do | |
if type(k) ~= 'number' then k = '"' .. k .. '"' end | |
s = s .. tbs:rep(tb) .. '[' .. k .. '] = ' .. dump(v, tbs, tb) | |
s = s .. ',\n' | |
end | |
tb = tb - 1 | |
return s .. tbs:rep(tb) .. '}' | |
else | |
return tostring(o) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment