If the title wasn’t as informative as needed, this is what I’m trying to do:
local alphabet = {a=1,b=2,c=3}
local function convert(text)
return print(alphabet[text])
end
If the title wasn’t as informative as needed, this is what I’m trying to do:
local alphabet = {a=1,b=2,c=3}
local function convert(text)
return print(alphabet[text])
end
Something like this should work, no need for numbers in the table since index of the letters can be used:
local alphabet = {"a","b","c","d","e","f"}
function convert(text)
local str = string.split(text,"")
local str2 = ""
for i,v in pairs(str) do
str2 ..= table.find(alphabet,str[i])
end
return print(str2)
end
convert("faded")
You could also use string.byte
to get the numbers instead of the alphabet table, string.byte("a") = 97
while string.byte("A") = 65
so you would need to subtract 96 to get the 1, if you want both A
and a
to = 1 then just do string.lower
as the first step in function.
If I understood you right, do you want to get letters/strings in an order?
I cannot tell everyone how much I appreciate them for their suggestions.
Here is a way better and efficient way to do it using string manipulation
local function convert(text)
local t = {}
local byte = string.byte
local a_byte = byte('a')
for i = 1, #text do
local n = byte(text, i, i) - a_byte + 1
t[i] = tostring(n)
end
return table.concat(t)
end
print(convert("faded"))
And here is the best way to do it without generating any string stuff, way faster and memory efficient xD
local function convert(text)
local n = 0
local byte = string.byte
local a_byte = byte('a')
local factor = 1
for i = #text, 1, -1 do
local digit = byte(text, i, i) - a_byte + 1
-- supports abcdefghi
assert(digit < 10 and digit > 0)
n = n + digit*factor
factor = factor * 10
end
return n
end
print(convert("faded"))
I understand this 2 pieces of code would probably seems like magic to a beginner, but here is my own videos where I explained the math and logic behind the techniques I used here:
Benchmark (LuaJIT) for 1000000 iterations:
my first function (string manipulation): 0.596711 second
my second function (cool math lol): 0.039504 second
my second function took 6% of the time the first function took xD
I wouldn’t even compare the memory usage between them, since the first function have to store tables and strings, while my second function only store 2 numbers or so xD