2

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?

2
  • How is your "anonymous function" relevant? It just adds a closure creation and a function call. Commented Jul 21, 2016 at 18:45
  • Not at all in fact for the "Memory consumptiom problem", just is something that I wanted to point out because sometimes I need to concatenate "inline" and do not reuse the function. Thanks! Commented Jul 22, 2016 at 14:02

1 Answer 1

3
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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This is very userfull! (Didn't know/remember about the table.concat). Sometimes I don't know what is more efficient because of the language shifting (When I use Java, then Lua or something like this). Very appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.