New in PICO-8 0.2.0.
- Gets the character corresponding to an ordinal (numeric) value.
- The ordinal value to be converted to a single-character string.
This function permits conversion of an ordinal value to the character it corresponds to, in the form of a single-character string.
The ordinal can be obtained either from some reference or data source, or by calling
ord() on a character in an existing string.
This can be used to easily produce a single character from its numeric representation:
> print(chr(104)) h > print(chr(105)) i > print(chr(33)) ! > print(chr(104)..chr(105)..chr(33)) hi!
This allows a string to be easily and rapidly created from a list of ordinals that represent it, possibly coming from memory or save data, or perhaps having been modified in some way, e.g. doing a naïve rot13 encryption:
> print(chr(104+13)..chr(105+13)) -- encrypt 104,105 => 117,118 uv > print(chr(117-13)..chr(118-13)) -- decrypt 117,118 => 104,105 hi
-- read a string from memory containing a pascal-format string: -- bytes 0,1: 16-bit length -- bytes 2->: character ordinals function memstr(mem, max_len) -- read the stored length local str_len = peek2(mem) -- limit the length in case of corruption str_len = mid(0, str_len, max_len) -- now build it from the stored ordinals that follow local s="" for addr = mem+2, mem+1+str_len do s = s..chr(peek(addr)) end return s end
ord() for the complementary
strmem() code example.)
Technical notes Edit
- If the
ordargument is a string, it will be converted internally to a number, if possible (with the same conditions as
tonum). This means that both
chr("49")will return the same value, "1", which is the character with ordinal 49.
- If the
ordargument is not in the range 0-255 (including after being converted from a string), a module 256 will be applied to move it back to this range.
- Types other than strings are not converted to numbers. Instead, a string with the null character "\0" will be returned.
chris similar to
string.charin native Lua, but is more flexible (while the string to number conversion was already part of
string.char, the modulo 256 operation was not).