Lua Programming/How to Lua/stringlib

FacilitiesEdit

string.byteEdit

string.charEdit

string.dumpEdit

string.findEdit

string.formatEdit

string.gmatchEdit

string.gsubEdit

string.lenEdit

UsageEdit

string.len(STRING)

DescriptionEdit

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

print (string.len("Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch"))    -- Returns 58
Embedded nul charactersEdit

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 stringEdit

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.lowerEdit

string.matchEdit

string.repEdit

string.reverseEdit

UsageEdit

string.reverse(STRING)

DescriptionEdit

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.subEdit

UsageEdit

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

DescriptionEdit

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 omittedEdit

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 negativeEdit

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 negativeEdit

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.upperEdit

Last modified on 12 April 2013, at 18:14