Advertisement
sub( str, start, [end] )
Gets the substring of a string.
str
The string.

start
The starting index, counting from 1 at the left, or -1 at the right.

end
The ending index, counting from 1 at the left, or -1 at the right. (default -1)

The start and end indices are inclusive, which is to say the characters at both indices will be included in the result.

In Lua, strings may contain any number of characters within them. The expression "" represents a string of 0 length. Lua doesn't actually expose a "character" type, but strings with a length of 1 are typically called characters. Whether extracting characters or substrings, the sub() function is the way to obtain portions of a string.

Single characters can be extracted from a string by passing the same index for both start and end, e.g. sub(s,i,i). As mentioned, the result is still a string, just with a length of 1.

When extracting single characters, sometimes the expression for the index is long or complex. Repeating it twice may be inconvenient or might cause side-effects. To avoid this problem, pass the desired index in start, but pass nil in end, e.g. sub(s,i,nil). The nil signals to sub() that the end index should be copied from start:

-- sometimes a index variable's name is lengthy or the expression is complex
mystring = "kalamazoo"
one = 1
two = 2
three = 3
-- making this cumbersome
z = sub(mystring, one+two*three, one+two*three)
-- but it can be simplified like so
z = sub(mystring, one+two*three, nil)

Additionally, negative indices can be very useful. They work exactly like positive indices, but index from the end of the string backwards. For instance:

> s="something"
> print(sub(s,-5))     -- get the string from the 5th-to-last char onwards
thing
> print(sub(s,-4,-3))  -- print "hi" since we know s ends with "thing"
hi
> print(sub(s,-2,nil)) -- print the 2nd-to-last character
n

Notes

PICO-8 adds the ability to represent characters as their ordinal value, a whole number in the range 0..255. There are two calls that can convert back and forth between the two representations:

  • To convert an ordinal number n to its single-character string counterpart, use chr(n).
  • To convert a single-character string c to its ordinal number counterpart, use ord(c).
  • To convert a single character at index i in a longer string s to its ordinal number, use ord(s, i).

Examples

print(sub("hello there", 1, 5))    -- hello
print(sub("hello there", -5))      -- there
print(sub("hello there", 7, 7))    -- t
print(sub("hello there", 7, nil))  -- t

See also

Community content is available under CC-BY-SA unless otherwise noted.