Sigma Octantis
Sigma Octantis

Reputation: 942

Lua table/list string cast/concat

Is there any method more efficient but simpler as the anonymous function use, when casting a list (A table with only one level) to string?

Why asking this? I Have heard that the string concatenation over and over in Lua is memory inefficient because Lua strings are immutable objects that have to be thrown to the garbage collector once used.

So with anonymous function usage I mean this:

local resources = {
    ["bread"] = 20,
    ["meat"] = 5,
    ["something"] = 99
};

local function getTheText()
    return "Resources:\n"..
        ( (function()
             local s = "";
             for k, v in pairs(resources) do
                 s = s.."\n\t"..k..": "..v.." units.";
             end
             return s;
        )())..
        "\nMore awesome info...";
   end
end

You know, for this time I could use a metafunction like a tostring on this table because it is not going to change, but if I use other anonymous tables I will not have this option.

Anyway I love the anonymous usage of functions so, it is not a problem for me.


Is there anything more efficient that does not require declaring functions? and is this more or less efficient than using a metamethod?

Upvotes: 2

Views: 901

Answers (1)

ryanpattison
ryanpattison

Reputation: 6251

local function getTheText()
    local temp = {"Resources:"}
    for k,v in pairs(resources) do
        temp[#temp + 1] = "\t"..k..": "..v.." units."
     end
     temp[#temp + 1] = "More Awesome info..."
     return table.concat(temp, "\n")
end

table.concat will build strings efficiently and use less memory than concatenating via s = s ...

This issue is covered in PIL

Upvotes: 3

Related Questions