Lua table.concat翻译成中文是:Lua表连接函数。

有没有办法使用table.concat的第二个参数来表示当前的表索引?

例如:

 t = {}
 t[1] = "a"
 t[2] = "b"
 t[3] = "c"

 X = table.concat(t,"\n")

table.concat的期望输出(X):

 "1 a\n2 b\n3 c\n"
点赞
用户1847592
用户1847592

不过有一个变通方法:

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')
2013-03-18 13:15:43
用户88888888
用户88888888

我不这么认为:例如,你如何告诉它键和值之间的分隔符应该是空格呢?

你可以编写一个通用的映射函数来完成你想要的操作:

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")
2013-03-18 13:18:58
用户513763
用户513763

简单的回答:不。

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) --然后可选指定每个项目的格式
Y = concatIndexed(t,'custom format %3d %s\n')
2013-03-18 13:19:42
用户13447666
用户13447666
function Util_Concat(tab, seperator)
  --如果分隔符(seperator)是空则使用原本的table.concat
  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是表输入的地方,separator可以为nil或字符串(如果为nil,则表现得像普通的table.concat)。

print(Util_Concat({"Hello", "World"}, "_"))
--输出
--Hello_world
2021-06-07 06:49:32