Reputation: 79
I'm trying to understand what's going on in the following function but I'm having trouble tracing through it.
function whatsthis(str)
local val = ""
local vtable = "?\029#sMb5\rY\041>hS\005Bm~2\021\016\024\023xN\019gRK\\;p!\002jJ_\t4:-\000vLiA]I=6l\018ec\0248\030w%7\b\0151,\003\004Z)9`{*kP\028F}o\v\n.[EfV\006^\001nC<U\027WQ&\022(\fTD\026Guz/+aO'q3d|H\025 \ay$\"X\017\0200r@t"
for i = 1, #str do
local b = str:byte(i)
if b > 0 and b <= 127 then
val = val .. string.char(vtable:byte(b))
else
val = val .. string.char(b)
end
end
return val
end
Part of the problem, I suppose, is that I've been given this exercise and I don't even know if vtable is a table or a string!
Example call:
string1 = whatsthis(",5MX")
I assume str:byte(i) converts ascii to bytes. ie. ",5MX" to 2c 35 4d 58 but I have no idea how it references vtable or why a variable that is already a byte needs to be re-cast in vtable:byte(b) again. It's clear ",5MX" references vtable through the intermediary byte but then I get lost and have no idea what gets returned to string1 or why.
To make matters worse....
string2 = whatsthis("\f4kp,X\026")
... is that parameter treated like a single string or two values, and how are the \ escapes handled in the function if not as just another character.
I hope I've been clear. I'm new to lua so I hope someone can shed some light here. Thanks in advance.
Upvotes: 1
Views: 132
Reputation: 26744
I don't even know if vtable is a table or a string!
vtable is always a string.
why a variable that is already a byte needs to be re-cast in vtable:byte(b) again
It's because it gets the numerical value of a character and then finds a character at a position with that index. On a quick glance it looks like it implements some sort of substitution cipher, where it replaces one character with a particular index (<=127) with a different one (taken from the table).
Upvotes: 1
Reputation: 28950
Part of the problem, I suppose, is that I've been given this exercise and I don't even know if vtable is a table or a string!
You assign something in double quotes to vtable, so it must be a string value.
local vtable = "?\029#sMb5\rY\..."
See https://www.lua.org/manual/5.4/manual.html#3
str:byte(i)
is syntactic sugar for string.byte(str, i)
See https://www.lua.org/manual/5.4/manual.html#3.4.10
string.byte(str, i)
will return the internal numeric code for character number i
in the string str
. So it gives you the byte value that represents that character.
See https://www.lua.org/manual/5.4/manual.html#pdf-string.byte
I assume str:byte(i) converts ascii to bytes. ie. ",5MX" to 2c 35 4d 58
Yes.
This code will check wether a character is part of the ASCII standard. If that's the case it will map it to the vtable string.
If it is part of the extended ASCII table it will use it as is
Compare print(whatsthis("ö"))
vs print(whatsthis("a"))
Upvotes: 2