[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: whats the easy way to dump a table as a string?
- From: Matt Campbell <mattc@...>
- Date: Fri, 07 Apr 2006 18:34:26 -0500
Hello Sam:
The book _Programming in Lua_ covers serialization of tables, both with
and without support for cycles. For your convenience, here's my
serialize function, which is based on the book's example without cycle
support but returns a string instead of writing to the current output
file. I hope this helps.
function serialize(o)
local t = type(o)
if t == "number" then
return tostring(o)
elseif t == "string" then
return string.format("%q", o)
elseif t == "table" then
local result = "{"
local nextIndex = 1
local first = true
for k, v in pairs(o) do
if first then
first = false
else
result = result .. ", "
end
if type(k) == "number" and k == nextIndex then
nextIndex = nextIndex + 1
else
if type(k) == "string" and string.find(k, "^[_%a][_%w]*$") then
result = result .. k
else
result = result .. "[" .. serialize(k) .. "]"
end
result = result .. " = "
end
result = result .. serialize(v)
end
result = result .. "}"
return result
else
return tostring(o)
end
end
--
Matt Campbell
Lead Programmer
Serotek Corporation
www.freedombox.info
"The Accessibility Anywhere People"