New in PICO-8 0.2.0.
- 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
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 parameter (which defaults 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!
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.
-- 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)) end end
chr() for the complementary
memstr() code example.)
Technical notes Edit
- If the
strargument is a number, it will be converted internally to a string. This means that both
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,
ordwill return nothing (most of the time, you can consider getting
nil, but inspecting the value will give different results, possibly Runtime Error).
- If the
indexargument is out of bound,
ordwill also return nothing. If the
strargument is an empty string, this is always the case.
ordis similar to
string.bytein native Lua, but it doesn't take a third argument for an end of range, only an index.