Lua Programming/stringlib
Facilities
editstring.byte
editstring.char
editstring.dump
editstring.find
editstring.format
editstring.gmatch
editstring.gsub
editstring.len
editUsage
editstring.len(STRING)
Description
editThe string.len function returns the length of the string argument.
print (string.len("Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch")) -- Returns 58
Embedded nul characters
editEmbedded nul characters do not terminate the string and are also counted by this function.
print (string.len("ab\000cd\000")) -- Returns 6
The length operator can also be used to determine the length of a string
editThe lua programming language provides a length operator, which can also be used to determine the length of a string:
print (#"Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch") -- Returns 58
string.lower
editstring.match
editstring.rep
editstring.reverse
editUsage
editstring.reverse(STRING)
Description
editThe string.reverse function can be used for reversing string and returns the string with its character order reversed:
print (string.reverse("anut fo raj a rof tun A")) -- A nut for a jar of tuna
string.sub
editUsage
editstring.sub(STRING, STARTPOS [, ENDPOS])
Description
editThe string.sub function returns a substring of the string argument from a start position, and an optional end position.
print (string.sub("cheese salad sandwich",8)) -- position 8 onwards gives us "salad sandwich" print (string.sub("cheese salad sandwich",1,12) -- positions 1 to 12 gives us "cheese salad"
The start position cannot be omitted, but the end position may be omitted
editNote that the start position is not optional, so for substrings starting at the first position, a parameter of one must be provided:
-- This does not work print (string.sub("cheese salad sandwich",,12) -- we cannot omit the start position -- To fix this, we must provide a substring position print (string.sub("cheese salad sandwich",1,12) -- we want a substring from position 1
The end position can be omitted or negative
editWithout an end position, the substring continues to the end of the string:
print (string.sub("cheese salad sandwich",8)) -- position 8 onwards gives us "salad sandwich"
String positions may be negative
editThe end position can be negative. A negative value indicates the number of characters from the end, with -1 meaning the last character, -2 meaning the last but one character, etc:
print (string.sub("cheese salad sandwich",-8)) -- start 8 characters from the end gives "sandwich" print (string.sub("cheese salad sandwich",1,-9)) -- drop " sandwich" to give "cheese salad"