FANDOM


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

Examples Edit

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

Pico-8 has no built-in way to associate letters 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)
end

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
end
 
function chartonum(c)
  return charnums[c] or 0
end

See also Edit