Lua table/list 字符串 cast/concat

Lua table/list string cast/concat

有没有比匿名函数更有效但更简单的方法,在投射列表时(A table只有一个级别) 到字符串?

为什么要问这个?我听说 Lua 中一遍又一遍的字符串连接是 内存效率低下 因为 Lua 字符串是 immutable 必须抛出的对象垃圾收集器曾经使用过。

因此使用 匿名函数 我的意思是:

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

你知道,这次我可以在 table 上使用 元函数,例如 tostring,因为它不是会改变,但如果我使用其他 anonymous tables 我将没有这个选项。

无论如何,我喜欢函数的匿名使用,所以这对我来说不是问题。


有没有比不需要声明函数更有效的方法?这比使用元方法更有效还是更不有效?

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 将有效地构建字符串并使用比通过 s = s ...

连接更少的内存

此问题已在 PIL

中介绍