'Lua string manipulation

This is my code

local function char(...) return string.char(...) end

local function addtok(text,token,C)
   text = text or ""
   local string = ""
   local count = 0
   for word in text:gmatch(("[^%s]+"):format(char(C))) do
      string = string..char(C)..word
   end
   string = string..char(C)..token
   print(string)
end

The function

addtok("Devotion Aura;Charger;Righteous Fury","Seal of Wisdom",59)

returns

";Devotion Aura;Charger;Righteous Fury;Seal of Wisdom"

but what I want is

"Devotion Aura;Charger;Righteous Fury;Seal of Wisdom"

possible fix: print(string.sub(string, 2))

any better solution?



Solution 1:[1]

local function addtok(text,token,C) 
   local string = (text or "").. string.char(C) .. token   
   print(string)
end

addtok("Devotion Aura;Charger;Righteous Fury","Seal of Wisdom",59)

Solution 2:[2]

The line string = string..char(C)..word will prepend the first semicolon. That's the issue with appending within a loop - you have to make an exception for either the last or the first element if you don't want a trailing or leading delimiter. In this case however, you should be using table.concat, both for performance (avoiding unnecessary string copies) and convenience of joining by delimiter:

local function char(...) return string.char(...) end

local function addtok(text,token,C)
   text = text or ""
   local words = {}
   local count = 0
   for word in text:gmatch(("[^%s]+"):format(char(C))) do
      table.insert(words, word)
   end
   local string = table.concat(words, char(C))..char(C)..token
   print(string)
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Piglet
Solution 2 LMD