Lua: Strings

From Mario Fan Games Galaxy Wiki
Revision as of 06:00, 6 August 2009 by Xgoff (talk | contribs) (Created page with '{{Lua}} Like most high-level languages with '''string''' support, Lua's strings are ''immutable''; once they have been created with some default data, they can't be changed. …')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Add to this template
 Standardwikimessagebox.png This article assumes the use of Lua 5.1.

Information may not be accurate or may need revision if you are using a different version.

Like most high-level languages with string support, Lua's strings are immutable; once they have been created with some default data, they can't be changed. As a result, operations like concatenation will actually return a new string without modifying the originals. For the most part, you won't notice this, but it can be important if you start building a string piecemeal.

Strings are considered objects in Lua, which means they can use methods. If the string library is used, you can use colon syntax with strings. Note that if "raw" strings are used in this manner, they need to be enclosed in parentheses, like so:

test = "hello"
test:upper() -- legal
"hello":upper() -- error
("hello"):upper() -- legal

Strings, like numbers, can be coerced in some cases—converted to another type: a number. This happens automatically in arithmetic operations such as adding a string to a number, but only if the string contains only characters that may appear in a number literal. There are two cases where Lua won't coerce a string: equality comparisons and table indexing; an error will be thrown in the first case, and in the second, 0 and "0" are completely different table indices.

Strings can be declared in a few ways, the most familiar is the " " and ' ' syntax, which may require escape sequences when appropriate. However, there is also a long string syntax which is useful in some cases, because it preserves line breaks and doesn't require you to escape characters... Well, it will preserve all line breaks except for a single optional one right after the opening bracket. A long string is declared using double square brackets: [[ ]]. However, there can also be different levels of these strings, denoted by how many '=' symbols appear between each pair of brackets, like [=[ ]=] for level 1 or [=====[ ]=====] for level 5. Long strings used in this manner can be nested, but nested strings won't "lose" their brackets when printed; these are more useful for block comments.

Like tables, the length of a string can be retrieved by the length operator #. Concatenation is carried out using the .. operator.