Skip to content

Instantly share code, notes, and snippets.

@nfrid
Last active June 19, 2022 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nfrid/2b4b62900d68f68d30f4ba82fbeeb02d to your computer and use it in GitHub Desktop.
Save nfrid/2b4b62900d68f68d30f4ba82fbeeb02d to your computer and use it in GitHub Desktop.
lua: dump any value as a formatted string
--- 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