lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> On 17 April 2010 18:33, Arseny Vakhrushev <arseny.vakhrushev@gmail.com> wrote:
>> Still no chances to hold cyclic references in tables correctly. It seems the thing will fail storing
>> someting like 't':
>>
>> local t = {}
>> table.insert(t, t)
>>
>> Be well,
>> Seny

> Thanks for the feedback, but I don't really understand the "cyclic
> reference" thing.
> How do you suggest I handle this issue?

Well, I'm not a big fan doing such serializations entirely in Lua (I do them in C), however, you may
look at the following code which I use for debugging purposes to get the idea.

-----------------------------------------------------
function dump(v, n, d, s)
        local n = n or 0
        local d = d or {}
        local r = ''
        local p = string.rep('  ', n)
        local t = type(v)
        if t == 'table' and not s then
                if d[v] then
                        return '{...}'
                end
                d[v] = true
                r = '{'
                local i = 0
                for tk, tv in pairs(v) do
                        r = r .. string.format('\n%s  %s => %s,', p, dump(tk, n + 1, d, true), dump(tv, n + 1, d))
                        i = i + 1
                end
                if i > 0 then
                        r = r .. '\n' .. p
                end
                r = r .. '}'
        elseif t == 'string' then
                r = '"' .. v .. '"'
        elseif t == 'number' or t == 'boolean' or t == 'nil' then
                r = tostring(v)
        else
                r = '(' .. tostring(v) .. ')'
        end
        return r
end
------------------------------------------------------

Usage example:

local t = { "hello", 123 }
table.insert(t, t)
print(dump(t))

---------------------------------


Be well,
Seny