Table.toString

From Multi Theft Auto: Wiki
Jump to navigation Jump to search

This function converts table to a string.

Syntax

string table.toString( table tab [ bool beautify = true, int recLvl = 0 ])

Required Arguments

  • tbl: The table to convert.

Optional Arguments

  • beautify: Should the string be beautified? (each entry is separated by tab)
  • recLvl: Depth of the table. beautify must be set to true in order for it to work

Returns

Returns string if table was successfully converted, false otherwise.

Click to collapse [-]
Shared function
function table.toString(tbl, beautify, recLvl)
    if beautify == nil then beautify = true end
    recLvl = recLvl or 0
    local str = '{'..(beautify and '\n' or '')
    local kStr
    local vStr
    for k,v in pairs(tbl) do
        for i=0,recLvl do
            str = str..(beautify and '\t' or '')
        end
        kStr = (type(k) == 'string' and '"%s"' or '%s')
        kStr = ('['..kStr..']'):format(k)
        vStr = (type(v) == 'table' and table.toString(v, beautify, recLvl+1) or v)
        str = str..kStr..' = '..vStr
		str = str..(next(tbl,k) and ',' or '')
        str = str..(beautify and '\n' or '')
    end
    if beautify then
        for i=1,recLvl do
            str = str..'\t'
        end
    end
    return str..'}'
end


Example

Click to collapse [-]
Shared function
local tbl = {
    'someKey',
    'someValue',
    1,56,true
}

local str = table.toString(tbl)
print(str)


Author: Tracer

See Also