Get string table

1

I'm trying to get a table as a string. EX:

tabela = {1, b=2, {c=3}}
print(getTableString(tabela))

If this function existed, and it worked, it would return:

-> tabela = {1, b=2, {c=3}}

Is there any way to do this?

    
asked by anonymous 22.11.2014 / 05:13

1 answer

1

This function prints the way you want it:

local function getTableString(t)

    local r = '{'

    for k, v in pairs(t) do
        if type(k) == 'number' then
            k = ''
        else
            k = k .. ' = '
        end
        if r ~= '{' then
            r = r .. ', '
        end
        r = r .. k
        if type(v) == 'table' then
            r = r .. getTableString(v)
        else
            r = r .. tostring(v)
        end
    end 

    r = r .. '}'

    return r

end

tabela = {1, b=2, {c=3}}
print(getTableString(tabela))

will return only the value of the table eg: {1, b=2, {c=3}

If you want to return as in your question, printing the table name, there is this option:

local function getTableStringWithName(t)

    local r, n = '{', ''

    if type(t) == 'string' then
        n = ' -> ' .. t .. ' = '
        t = loadstring('return ' .. t)()
    end

    for k, v in pairs(t) do
        if type(k) == 'number' then
            k = ''
        else
            k = k .. ' = '
        end
        if r ~= '{' then
            r = r .. ', '
        end
        r = r .. k
        if type(v) == 'table' then
            r = r .. getTableStringWithName(v)
        else
            r = r .. tostring(v)
        end
    end 

    r = r .. '}'

    return n .. r

end

tabela = {1, b=2, {c=3}}
print(getTableStringWithName('tabela'))

Note that the table has to be passed by string, so you can get its name.

    
19.12.2014 / 23:39