Skip to content

Instantly share code, notes, and snippets.

@kentkrantz
Last active November 18, 2020 09:32
Show Gist options
  • Save kentkrantz/e43020d55a6b2a3648a6bfc140a6a23a to your computer and use it in GitHub Desktop.
Save kentkrantz/e43020d55a6b2a3648a6bfc140a6a23a to your computer and use it in GitHub Desktop.
Convert lua table to string
function table.val_to_str ( v )
if "string" == type( v ) then
v = string.gsub( v, "\n", "\\n" )
if string.match( string.gsub(v,"[^'\"]",""), '^"+$' ) then
return "'" .. v .. "'"
end
return '"' .. string.gsub(v,'"', '\\"' ) .. '"'
else
return "table" == type( v ) and table.tostring( v ) or
tostring( v )
end
end
function table.key_to_str ( k )
if "string" == type( k ) and string.match( k, "^[_%a][_%a%d]*$" ) then
return k
else
return "[" .. table.val_to_str( k ) .. "]"
end
end
function table.tostring( tbl )
local result, done = {}, {}
for k, v in ipairs( tbl ) do
table.insert( result, table.val_to_str( v ) )
done[ k ] = true
end
for k, v in pairs( tbl ) do
if not done[ k ] then
table.insert( result,
table.key_to_str( k ) .. "=" .. table.val_to_str( v ) )
end
end
return "{" .. table.concat( result, "," ) .. "}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment