Ord

From Pico-8 Wiki
Jump to navigation Jump to search

New in PICO-8 0.2.0.

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

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-value
The ordinal value(s) of the count character(s) at index in str

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"))
104
> print(chr(104))
h

However, the optional index and count parameters (which default to 1) may be used to iterate over 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!
> ord("hi!", 1, 3) -- returns 104, 105, 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

-- write a string to memory, in pascal format: 
--  bytes 0,1: 16-bit length
--  bytes 2->: character ordinals
function pokestr(dst_mem, src_str, max_len)
  -- limit its length to avoid buffer overruns
  local len = min(#src_str, max_len)
  -- write the 16-bit length to the first 2 bytes
  poke2(dst_mem, len)
  -- followed by that many character ordinals as bytes
  poke(dst_mem + 2, ord(src_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(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