字符串拼接成段落,换行符(\n)如何只执行n-1次

场景
假设有一个table结构如下:

props = { {id = 1, name = "攻击", value = https://www.it610.com/article/1000}, {id = 2, name ="防御", value = https://www.it610.com/article/1500}, {id = 3, name ="生命", value = https://www.it610.com/article/2000} }

然后实现以下格式的输出:
攻击 + 1000
防御 + 1500
生命 + 2000
代码
【字符串拼接成段落,换行符(\n)如何只执行n-1次】第一种做法:
local len = table.getn(props) local desc = "" for i, v in ipairs(props) do desc = desc .. v.name .. " : " .. v.value if i < len then desc = desc .. "\n" end end print(desc)

第二种做法:
local desc = "" local sep = "" for i, v in ipairs(props) do desc = desc .. sep .. v.name .. " : " .. v.value sep = "\n" end print(desc)

总结
个人觉得第二种方法比较高大上,同时也适合一些需要‘,’分隔之类的,不一样只是‘\n’。

    推荐阅读