PICO-8 Wiki
sub( str, start, [end] )
Gets the substring of a string.
The string.

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

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.

As of v0.2.5, the recommended way to extract single characters is s[i].

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
> print(sub(s,-4,-3))  -- print "hi" since we know s ends with "thing"
> print(sub(s,-2,nil)) -- print the last two 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).


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[]