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. 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).

Examples Edit

print(sub("hello there", 1, 5))    -- hello
print(sub("hello there", -5))      -- there

PICO-8 has no built-in way to associate characters with numbers. You can simulate this using a string as a look-up table:

-- this example uses a limited subset, but 
-- you could also use escape codes to 
-- include all chars from '\1' to '\255'.
chars = ' !"#%\'()*+,-./0123456789:;<=>?abcdefghijklmnopqrstuvwxyz[]^_{~}'
function numtochar(v)
  return sub(chars, v, v)

Converting a character back to a number is a bit more cumbersome but can be done by creating a reverse-lookup table from the string:

charnums = {}
for i=1,#chars do
  charnums[sub(chars, i, i)] = i
function chartonum(c)
  return charnums[c] or 0

See also Edit

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