Lua table.concat
Asked Answered
M

4

6

Is there a way to use the arg 2 value of table.concat to represent the current table index?

eg:

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

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

desired output of table concat (X):

 "1 a\n2 b\n3 c\n"
Manure answered 18/3, 2013 at 13:6 Comment(0)
T
12

Simple answer : no.

table.concat is something really basic, and really fast.

So you should do it in a loop anyhow.

If you want to avoid excessive string concatenation you can do:

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')
Thao answered 18/3, 2013 at 13:19 Comment(1)
Exactly, thanks. BTW, if you spot an error like this, feel free to edit the answer yourself, as you have enough privileges to edit.Thao
S
8

I don't think so: how would you tell it that the separator between keys and values is supposed to be a space, for example?

You can write a general mapping function to do what you'd like:

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")
Send answered 18/3, 2013 at 13:18 Comment(0)
A
4

No. But there is a work around:

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')
Atrocious answered 18/3, 2013 at 13:15 Comment(0)
P
0
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

usage tab is where the table input is and seperator be both nil or string (if it nil it act like ordinary table.concat)

print(Util_Concat({"Hello", "World"}, "_"))
--Prints
--Hello_world
Punner answered 7/6, 2021 at 6:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.