PICO-8 Wiki
Advertisement
ord( str, [index,] [count] )
Gets the ordinal (numeric) versions of an arbitrary number of characters in a string.
str
The string whose character(s) are to be converted to ordinal(s).

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

count
The number of characters to read from the string. Default is 1.

return-values
The ordinal value(s) of the count character(s) at index in str, as a tuple.

This function permits conversion of an arbitrary number of characters in a string to the ordinal(s) corresponding to them, which in turn can be converted back to the original characters 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 a single-character string, to convert that character to an ordinal:

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

However, the optional index and count parameters (which default to 1) may be used to return multiple characters' ordinals from a longer string:

> print(ord("hi!"))
104
> print(ord("hi!", 2))
105
> print(ord("hi!", 3))
33
> print(chr(104)..chr(105)..chr(33))
hi!
> a, b, c = ord("hi!", 1, 3) -- returns 104, 105, 33
> print(b)
105
> print(chr(b))
i
> print(chr(a, b, c))
hi!

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

This implements writing a length-prefixed "Pascal" string to memory:

-- write a string to memory, in pascal format: 
--  bytes 0,1: 16-bit length
--  bytes 2->: character ordinals
function pokestr(mem_addr, str, max_len)
  -- limit its length to avoid buffer overruns
  local len = min(#str, max_len)
  -- write the 16-bit length to the first 2 bytes
  poke2(mem_addr, len)
  -- followed by that many character ordinals as bytes
  poke(mem_addr + 2, ord(str, 1, len))
end

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

Technical notes[]

  • If the str argument is a number, it will be converted internally to a string. This means that both ord(789, 2) and ord("789", 2) will return the same value, 56, which is the ordinal for the second digit's character, '8'.
  • Types other than numbers are not converted to strings. Instead, ord() will return nothing. Usually this is converted to a nil, but inspecting the value may produce different results, possibly a Runtime Error.
  • ord() is similar to string.byte() in native Lua, but that version doesn't take a third argument for an end of range, only an index.

See also[]

Advertisement