Convert array to string in LUA

11,185

To be clear, customLog is a table - that is, an associative array of key value pairs. Here’s an easy way to iterate over all key/value pairs and concatenate the pairs into one string:

s = ""

t = {"a", "b", "c", 123, 456, 789} -- sample table
t.someKey = "some value" -- just an extra key value, to show that keys can be strings too

for k, v in pairs(t) do
    s = s .. k .. ":" .. v .. "\n" -- concatenate key/value pairs, with a newline in-between
end

print(s)

Of course, if the value of a key is another table {}, then you will need some extra logic to recursively iterate over these nested tables. I’ll leave that for you as an exercise :)

EDIT 1: Print table as string, showing variable values

s = ""
local ID = 123
local Numbers = 456
local Log = { {Group = ID, Pos = Numbers}, {Group = ID, Pos = Numbers} }

s = s .. "{"
for k, v in next, Log do
    s = s .. "{"

    for vk, vv in next, v do
        if next(v, vk) ~= nil then
            s = s .. vk .. " = " .. vv .. ", "
        else
            s = s .. vk .. " = " .. vv  
        end
    end

    if next(Log, k) ~= nil then
        s = s .. "}, "
    else
        s = s .. "}"
    end

end
s = s .. "}"

print(s)

EDIT 2: Print table as string, showing variable names

s = ""
local ID = 123
local Numbers = 456
local Log = { {Group = ID, Pos = Numbers}, {Group = ID, Pos = Numbers} }

s = s .. "{"
for k, v in next, Log do
    s = s .. "{"

    i = 1
    for vk, vv in next, v do
        name = debug.getlocal(1, i)
        if next(v, vk) ~= nil then
            s = s .. vk .. " = " .. name .. ", "
        else
            s = s .. vk .. " = " .. name
        end
        i = i + 1
    end

    if next(Log, k) ~= nil then
        s = s .. "}, "
    else
        s = s .. "}"
    end

end
s = s .. "}"

print(s)
Share:
11,185
A Hamburgler
Author by

A Hamburgler

Updated on June 04, 2022

Comments

  • A Hamburgler
    A Hamburgler almost 2 years

    Trying to convert this to a string customLog2 = {} Which will really look like Log = { {Group = ID, Pos = Numbers}, {Group = ID, Pos = Numbers} } I tried this

    local Data = string.format( "LogBook = %s ", customLog2 )
    

    But Because CustomLog is an array and not a string or a number I cant insert it. Im trying to get the array into a string for this VariableFile:write(Data) So if anyone can help that would be awesome thanks.

    So I want my Output to look like this "local Data = string.format( "LogBook = %s ", customLog2 )" so I can use :write then in my newly created file it should look like this Log = { {Group = ID, Pos = Numbers}, {Group = ID, Pos = Numbers} }

    So this function works expect one thing.

    function TableSerialization(t, i)
        local text = "{\n"
        local tab = ""
        for n = 1, i + 1 do                                                                 --controls the indent for the current text line
            tab = tab .. "\t"
        end
        for k,v in pairs(t) do
            if type(k) == "string" then
                text = text .. tab .. "['" .. k .. "'] = "
            else
                text = text .. tab .. "[" .. k .. "] = "
            end
            if type(v) == "string" then
                text = text .. "'" .. v .. "',\n"
            elseif type(v) == "number" then
                text = text .. v .. ",\n"
            elseif type(v) == "table" then
                text = text .. TableSerialization(v, i + 1)
            elseif type(v) == "boolean" then
                if v == true then
                    text = text .. "true,\n"
                else
                    text = text .. "false,\n"
                end
            elseif type(v) == "function" then
                text = text .. v .. ",\n"
            elseif v == nil then
                text = text .. "nil,\n"
            end
        end
        tab = ""
        for n = 1, i do                                                                     --indent for closing bracket is one less then previous text line
            tab = tab .. "\t"
        end
        if i == 0 then
            text = text .. tab .. "}\n"                                                     --the last bracket should not be followed by an comma
        else
            text = text .. tab .. "},\n"                                                    --all brackets with indent higher than 0 are followed by a comma
        end
        return text
    end
    

    My input array lets say looks like this Log = { Group = WestAPC } now this does not work because WestAPC is not a string but if WestAPC looks like this "WestAPC" it works. I need it to not be in string form.

  • A Hamburgler
    A Hamburgler almost 6 years
    Close but not exactly what I needed. I need to literally take my array and put it into the other file exactly how it is. So an example of my array would be Log = { {Group = ID, Pos = Numbers}, {Group = ID, Pos = Numbers} }
  • brianolive
    brianolive almost 6 years
    @AHamburgler I’ve edited my answer. I am sure there are other permutations to this solution, ways to tweak the logic, etc. Getting variable names (edit 2, above) relies on the table values actually being local upvalues, sooo the final solution depends on your exact situation. I hope this helps you arrive at the code you need.
  • A Hamburgler
    A Hamburgler almost 6 years
    Really appreciate you help it does work except for some reason it wont transfer the variables over. Example it will say group = self instead of 123.
  • brianolive
    brianolive almost 6 years
    @AHamburgler Glad to help. “self” must be defined somewhere in your code. It is not a built-in symbol in Lua (the concept of self is, with the colon operator, but not the name “self”. Up to you if you want to post more code - we could try to get this question across the finish line.
  • A Hamburgler
    A Hamburgler almost 6 years
    I literally took you code and tested it and it came out the other end with group = self and Pos = event. They are not defined anywhere.
  • brianolive
    brianolive almost 6 years
    @AHamburgler Are you using edit 1 or 2? What environment are you programming in - e.g., are you developing in a game scripting environment (Roblox, Corona, etc.) or just your own Lua files? Finally, if you are using edit 2, then you may have other local variables defined before ID and Numbers. Manually increment the i counter variable - that will query other local variables on the stack.
  • A Hamburgler
    A Hamburgler almost 6 years
    I am scripting for a game called DCS. I used Example two as one did not work. I also tried to replace the ID and Numbers varibales with actual numbers. so it looks like Log = { {Group = 12, Pos = 11}, {Group = 1, Pos = 112} } and still came out the other end as Self and event. Sorry for the late reply by the way.