- Gets the character(s) corresponding to ordinal (numeric) value(s).
- ord [, ord2, [... ordn]]
-
- Zero or more ordinal values (typically one) to be converted into characters in a string.
- return-value
-
- A string consisting of as many characters as there were ordinal values. Default output is an empty string.
This function permits conversion of an arbitrary number of ordinal values to the character(s) they correspond to, in the form of a string.
The ordinal(s) can be obtained either from some reference or data source, or by calling ord()
on one or more characters in an existing string.
This can be used to easily produce characters from their numeric representations:
> print(chr(104)) h > print(chr(105)) i > print(chr(33)) ! > print(chr(104)..chr(105)..chr(33)) -- concatenate 3 single characters hi! > print(chr(104, 105, 33)) -- or have chr() return a 3-character string hi!
This allows a string to be easily and rapidly created from a list of ordinals that represent it. There are many ways this might be done, including reading strings from memory or save data, or sending strings through an arithmetic encryption/decryption process.
Examples[]
This implements reading a length-prefixed "Pascal" string from memory:
-- read a string from memory containing a pascal-format string:
-- bytes 0,1: 16-bit length
-- bytes 2->: character ordinals
function peekstr(mem_addr, max_len)
-- read the 16-bit length stored in the first 2 bytes
local len = peek2(mem_addr)
-- limit the length in case it is corrupt
len = min(len, max_len)
-- build a string from the stored ordinal bytes after the 2 'len' bytes
return chr(peek(mem_addr + 2, len))
end
(See ord()
for the complementary pokestr()
code example.)
This is a rather naïve implementation of the simple ROT13 cipher most programmers learn about during their education, which can be used both to encode and decode strings:
function rot13(s)
local r = ""
for c in all(s) do
if c>='a' and c<='z' then
-- subtract ord('a') == 97 to make the range 0..25,
-- but also add 13 to rotate the alphabet by half,
-- giving -97 + 13 = -84, then modulo and add 97 back
c = chr((ord(c) - 84) % 26 + 97)
end
r = r..c
end
return r
end
> print(rot13("omg!")) bzt! > print(rot13("bzt!")) omg!
Technical notes[]
- Every
ord
argument is ultimately treated as an 8-bit unsigned integer, as ifchr()
's implementation begins withord &= 0xff
. In other words, it is floored to a whole number, modulo 256.
- If an
ord
argument is a string that satisfies the conditions oftonum(ord)
, it will be converted internally to a number. This means that bothchr(33)
andchr("33")
will return "!".
- Other types, and strings that cannot be converted to numbers, will be treated as if ord were 0.
chr()
is similar tostring.char()
in native Lua, but is more flexible. For instance, while the string to number conversion was already part ofstring.char
, the modulo 256 operation was not.