有没有一种方法可以使用table.concat的第二个参数来表示当前表的索引?
例如:
t = {}
t[1] = "a"
t[2] = "b"
t[3] = "c"
X = table.concat(t,"\n")
表格连接(X)的期望输出:
"1 a\n2 b\n3 c\n"
有没有一种方法可以使用table.concat的第二个参数来表示当前表的索引?
例如:
t = {}
t[1] = "a"
t[2] = "b"
t[3] = "c"
X = table.concat(t,"\n")
表格连接(X)的期望输出:
"1 a\n2 b\n3 c\n"
简单回答:不可以。
table.concat
是非常基础且非常快速的操作。
因此,您无论如何都应在循环中执行它。
如果您想避免过度的字符串连接,可以使用以下方法:
function concatIndexed(tab,template)
template = template or '%d %s\n'
local tt = {}
for k,v in ipairs(tab) do
tt[#tt+1]=template:format(k,v)
end
return table.concat(tt)
end
X = concatIndexed(t) -- and optionally specify a certain per item format
Y = concatIndexed(t,'custom format %3d %s\n')
我不这么认为:比如说,你怎么告诉它键和值之间的分隔符应该是空格呢?
你可以编写一个通用的映射函数来实现你想要的功能:
function map2(t, func)
local out = {}
for k, v in pairs(t) do
out[k] = func(k, v)
end
return out
end
function joinbyspace(k, v)
return k .. ' ' .. v
end
X = table.concat(map2(t, joinbyspace), "\n")
local n = 0
local function next_line_no()
n = n + 1
return n..' '
end
X = table.concat(t,'\0'):gsub('%f[%Z]',next_line_no):gsub('%z','\n')
function Util_Concat(tab, seperator)
if seperator == nil then return table.concat(tab) end
local buffer = {}
for i, v in ipairs(tab) do
buffer[#buffer + 1] = v
if i < #tab then
buffer[#buffer + 1] = seperator
end
end
return table.concat(buffer)
end
使用 tab
参数来指定表格输入,分隔符可以是 nil
或字符串(如果为 nil
,则表现类似于普通的 table.concat
)
print(Util_Concat({"Hello", "World"}, "_"))
--Prints
--Hello_world