Affichage des articles dont le libellé est lua. Afficher tous les articles
Affichage des articles dont le libellé est lua. Afficher tous les articles

vendredi, mars 28, 2008

Universal lua tostring

Universal tostring (also available here)


function table_print (tt, indent, done)
done = done or {}
indent = indent or 0
if type(tt) == "table" then

local sb = {}
for key, value in pairs (tt) do
table.insert(sb, string.rep (" ", indent)) -- indent it

if type (value) == "table" and not done [value] then
done [value] = true

table.insert(sb, "{\n");
table.insert(sb, table_print (value, indent + 2, done))
table.insert(sb, string.rep (" ", indent)) -- indent it
table.insert(sb, "}\n");
elseif "number" == type(key) then

table.insert(sb, string.format("\"%s\"\n", tostring(value)))
else
table.insert(sb, string.format("%s = \"%s\"\n", tostring (key), tostring(value)))
end

end
return table.concat(sb)
else
return tt .. "\n"
end

end

function to_string( tbl )
if "nil" == type( tbl ) then
return tostring(nil)
elseif "string" == type( tbl ) then
return tbl
elseif "table" == type( tbl ) then
return table_print(tbl)
else
tostring(tbl)
end
end

Example


print(to_string({"Lua",user="Mariacher",{{co=coroutine.create(function() end),{number=12345.6789}},
func=function() end}, boolt=true}))


This prints

"Lua"
{
{
{
number = "12345.6789"
}
co = "thread: 0212B848"
}
func = "function: 01FC7C70"
}
boolt = "true"

user = "Mariacher"