Skip to main content

  | मौसम…

411 समाचार
Public archive edition · Attributed source reporting with original dates · AI drafts are excluded

411 REFERENCE · Wikibooks

Lua Programming/stringlib

Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.

Facilities string.byte string.char string.dump string.find string.format string.gmatch string.gsub string.len Usage string.len(STRING) Description The string.len /function/ returns the length of the /string/ argument. print (string.len("Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch")) -- Returns 58 Embedded nul characters 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 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 string.match string.rep string.reverse Usage string.reverse(STRING) Description 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 Usage string.sub(STRING, STARTPOS [, ENDPOS]) Description 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 Note that the start position is not optional, so for /substring/s 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 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 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