As all computers are digital (i.e. numeric) devices, all letters are of course internally just some numbers. There is just some encoding rule, determining which number means which letter. ASCII is perhaps most well-known, widely-used and also basis for others more advanced (e.g. Unicode or UTF-8 are extensions over ASCII).
There are just two functions to manipulate these codes. Wait for "exercises" section to learn why you may need it at all.
name = 'Ada'
print(name:byte())
print(name:byte(2), name:byte(3))
The function :byte
without arguments returns the numeric code of the first letter of the text string - in our case
the code of capital A
- it is 65
and some programmers even remember this by heart.
When numeric argument is provided (2
or 3
in our case) - this simply means to return the code for the second or
third letters of the string, correspondingly. They'll be 100
and 97
. Here you can note several things:
32
(magic number!)d
is larger than code for a
exactly by 3
which hints that codes simply follow alphabet.Backward conversion, from code to character, happens with string.char(...)
function. It is singular in that it doesn't
use colon in its syntax (because it doesn't have text variable to be applied to):
print(string.char(65+26-3))
This prints X
- as we remember, 65
is for A
and since letters follow alphabetically, adding 26
gets us just after Z
(which is the last 26-th letter of the Latin alphabet) - then we subtract 3
positions as we remember X
is the third from the end.
Create a loop which prints characters with codes starting from 32
and ending with 63
. Ideally arrange them into
four lines of eight characters each, for better visibility.
Try solving Caesar Shift Cipher problems on this site.