Pick Table in string form

Asked

Viewed 133 times

1

I’m trying to get a string table. EX:

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

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

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

Is there any way to do that?

  • I think there’s like, but it’s not something so trivial (but not complicated). If I have time I do something but I don’t promise. I think you essentially have to put this text in your hand. You have to take the variable name, take the names of the elements and values in the table. It does not mean that it would solve any situation but it will already complicate. For example, it would be a problem to have the existence of nil. Maybe there’s some other way better and simpler, maybe using some kind of insight, but I don’t know.

  • I don’t understand your problem... What you want is to get a variable using its name in a string?

  • See http://lua-users.org/wiki/TableSerialization.

1 answer

1

This function prints in the way you want:

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))

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

If you want to return as in your question, printing 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 it is possible to get its name.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.