Home > Blockchain >  Lua string manipulation
Lua string manipulation

Time:03-01

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?

CodePudding user response:

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)

CodePudding user response:

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
  • Related