String

The String module provides various extensions on the default Lua string library.

Separated Strings

One common pattern is to store lists of elements as a string with a fixed separator. The String module provides two APIs to help facilitate this as demonstrated below.

local MyModule = select(2, ...).MyModule
local String = MyModule:From("LibTSMUtil"):Include("Lua.String")

local SEP = ","
local favoriteClasses = strjoin(SEP, "Rogue", "Mage", "Warrior")

print(String.SeparatedCount(favoriteClasses, SEP)) -- 3
print(String.SeparatedContains(favoriteClasses, SEP, "Rogue")) -- true
print(String.SeparatedContains(favoriteClasses, SEP, "Hunter")) -- false

for class in String.SplitIterator(favoriteClasses, SEP) do
   print(class)
end
-- Rogue
-- Mage
-- Warrior

API

class Lua.String: LibTSMModule
staticmethod SafeSplit(str: string, sep: string, resultTbl?: table): string[]

Splits a string in a way which won’t cause stack overflows for large inputs.

The lua strsplit function causes a stack overflow if passed large inputs. This API fixes that issue and also supports separators which are more than one character in length.

Parameters:
  • str (string) – The string to be split

  • sep (string) – The separator to use to split the string

  • resultTbl? (table) – An optional table to store the result in

staticmethod Escape(str: string): string

Escapes any magic characters used by lua’s pattern matching.

Parameters:

str (string) – The string to be escaped

staticmethod SeparatedContains(str: string, sep: string, value: string): boolean

Check if a string which contains multiple values separated by a specific string contains the value.

Parameters:
  • str (string) – The string to be searched

  • sep (string) – The separating string

  • value (string) – The value to search for

staticmethod SeparatedCount(str: string, sep: string): number

Gets the count of separated string parts.

Parameters:
  • str (string) – The string to count the parts in

  • sep (string) – The separating string

staticmethod SplitIterator(str: string, sep: string): fun(): string

Iterates over the parts of a string which are separated by a character.

Parameters:
  • str (string) – The string to be split

  • sep (string) – The separator to use to split the string

Returns:

_1 (fun(): string) – Iterator with fields: part

staticmethod FormatToMatchPattern(str: string): string

Generates a pattern matching string from a format string.

Parameters:

str (string) – The format string