Chr

From Pico-8 Wiki
Jump to navigation Jump to search

New in PICO-8 0.2.0.

chr( ord [, ord1, ordn] )
Gets the character(s) corresponding to an ordinal(s) (numeric) value.
ord [, ord1, ordn]
The ordinal value to be converted to a single-character string. Accepts an array of ordinals and will return a string of characters

return-value
A string consisting of a single character corresponding to the given ordinal number or a string of characters if an array was provided

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

New in version, `v0.2.4`, `chr()` will acecpt an array of ordinals and return a string of associtated characters:

> m = chr(112,105,99,111,45,56)
> print(m)
PICO-8

Technical Note

If chr() is called with no arguments, it will behave as if it had been passed a 0 and therefore it will return the nul character ("\0"). It is not clear whether or not this default value is intended, so it is probably not safe to rely on it.

Examples

-- read a string from memory containing a pascal-format string:
--  bytes 0,1: 16-bit length
--  bytes 2->: character ordinals
function peekstr(src_mem, max_len)
  -- read the 16-bit length stored in the first 2 bytes
  local len = peek2(src_mem)
  -- limit the length in case it is corrupt
  len = mid(0, len, max_len)
  -- build a string from the stored ordinal bytes after the 2 'len' bytes
  return chr(peek(src_mem + 2, len))
end

(See ord() for the complementary pokestr() code example.)

Technical notes

  • If the ord argument 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) and chr("49") will return the same value, "1", which is the character with ordinal 49.
  • If the ord argument 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.
  • chr is similar to string.char in native Lua, but is more flexible (while the string to number conversion was already part of string.char, the modulo 256 operation was not).

See also