Lua Programming/How to Lua/stringlib

From Wikibooks, open books for an open world
Jump to: navigation, search

Facilities[edit]

string.byte[edit]

string.char[edit]

string.dump[edit]

string.find[edit]

string.format[edit]

string.gmatch[edit]

string.gsub[edit]

string.len[edit]

Usage[edit]

string.len(STRING)

Description[edit]

The string.len function returns the length of the string argument.

print (string.len("Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch"))    -- Returns 58
Embedded nul characters[edit]

Embedded 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[edit]

The 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[edit]

string.match[edit]

string.rep[edit]

string.reverse[edit]

Usage[edit]

string.reverse(STRING)

Description[edit]

The 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[edit]

Usage[edit]

string.sub(STRING, STARTPOS [, ENDPOS])

Description[edit]

The 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[edit]

Note 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[edit]

Without 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[edit]

The 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"

string.upper[edit]