PICO-8 Wiki
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. To extract a single character, use the same value for both, e.g. sub(s,i,i).

Note that negative indices can be very useful. For instance, to get the rightmost four characters of a string, one simply writes sub(s,-4).

Notes[]

Individual characters can be extracted from a string by supplying the same index for both start and end. The result is still technically a string, but with a length of exactly 1. This is the way Lua typically represents individual characters.

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

See also[]