How to concatenate strings into one using loop?

11,886

Solution 1

There is no append operator for strings. Strings are immutable values.

The .. operator concatenates two string, producing a third string as a result:

local b = "con"
local c = "catenate"
local a = b .. c  -- "concatenate"

The table.concat function concatenates strings in a table, producing a string result:

local t = { "con", "catenate" }
local a = table.concat(t)  -- "concatenate"

local t = { "two", "words" }
local a = table.concat(t, " ") -- "two words"

The string.format function takes a format pattern with a list of compatible values, producing a string result:

local b = 2
local c = "words"
local a = string.format("%i %s", b, c)  -- "2 words"

local t = { 2, "words" }
local a = string.format("%i %s", unpack(t))  -- "2 words"

If you are accumulating a lot of strings that you eventually want to concatenate, you can use a table as a temporary data structure and concatenate when you are done accumulating:

local t = {}
for i = 1, 1000 do
    table.insert(t, tostring(i))
end
local a = table.concat(t) -- "1234...9991000"

For a very large number of strings, you can concatenate incrementally. See LTN 9: Creating Strings Piece by Piece and related discussions.

Solution 2

You should try the table.concat method.

Maybe this other question can help you:

Share:
11,886
user3159120
Author by

user3159120

Updated on June 04, 2022

Comments

  • user3159120
    user3159120 almost 2 years

    can someone help me with string concatenate problem. I read data from register. It's function utf(regAddr, length). I get table with decimal numbers, then I transform it into hex and to string in loop. I need concatenate these strings into one. there is not in Lua something like .= operator

    function utf(regAddr, length)
      stringTable = {} 
      table.insert(stringTable, {mb:readregisters(regAddr-1,length)})
    
      for key, value in pairs(stringTable) do
        for i=1, length do
          v = value[i]
          v = lmcore.inttohex(v, 4)
          v = cnv.hextostr(v)   
          log(v)
        end  
      end
    end
    
    -- function(regAddr, length)
    utf(30,20)
    

    enter image description here

  • user3159120
    user3159120 over 10 years
    Hi, I tried this function but for functions lmcore.inttohex and cnv.hextostr I need number no table. Some kind of append operator in loop seems to be solution, but I!m not sure how to do it
  • user3159120
    user3159120 over 10 years
    Thanks a lot Tom, your last piece of code works well and helped me