New in PICO-8 0.2.0.

ord( str, [index] )
Gets the ordinal (numeric) version of a character in a string.
The string whose character is to be converted to an ordinal.

The index of the character in the string. Default is 1, the first character.

This function permits conversion of a character in a string to an ordinal corresponding to that character, which in turn can be converted back to the character with chr().

If the string passed in is missing or empty, or the index is outside of the extents of the string, nil will be returned.

Typically this would be called with one single-character string, to convert that character to an ordinal:

> print(ord("h"))
> print(chr(104))

However, the optional index parameter (which defaults to 1) may be used to iterate over a longer string:

> print(ord("hi!"))
> print(ord("hi!", 2))
> print(ord("hi!", 3))
> print(chr(104)..chr(105)..chr(33))

This allows a string to be easily and rapidly converted to the list of ordinals that represent it. These ordinals may be manipulated and then possibly converted back to a string, saved to memory, or placed in save data.

Examples Edit

-- write a string to memory, in pascal format: 
--  bytes 0,1: 16-bit length
--  bytes 2->: character ordinals
function strmem(str, mem, max_len)
  -- limit its length to avoid memory overruns
  local str_len = min(#str, max_len)
  -- write the length
  poke2(mem, str_len)
  -- followed by the character ordinals
  for i = 1, str_len do
    poke(mem + 1 + i, ord(str, i))

(See chr() for the complementary memstr() code example.)

Technical notes Edit

  • If the str argument is a number, it will be converted internally to a string. This means that both ord(123) and ord("123") will return the same value, 49, which is the ordinal for the character '1'.
  • Types other than numbers are not converted to strings. Instead, ord will return nothing (most of the time, you can consider getting nil, but inspecting the value will give different results, possibly Runtime Error).
  • If the index argument is out of bound, ord will also return nothing. If the str argument is an empty string, this is always the case.
  • ord is similar to string.byte in native Lua, but it doesn't take a third argument for an end of range, only an index.

See also Edit

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