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.
- The number of characters to read from the string. Default is 1.
- 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
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
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.
-- 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
chr() for the complementary
peekstr() code example.)
- 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.