'Why does "array[index]" return "nil"?

this problem seems very simple but I cannot find a solution for it, actually I don't even know what is wrong!!!

So basically I have this Lua code:

io.write("\nPlease provide the message to be decyphered: ")
message = io.read()
seq = #message
ffib = {}
a = 0
b = 1
c = a + b
fib = 0
while c < (seq - 10) do
    fib = fib + 1
    ffib[fib] = c
    a = b
    b = c
    c = a + b
end
decyphered = ""
for i = 1,seq do
    decyphered = table.concat{decyphered, message:sub(ffib[i],ffib[i])}
end
io.write("\nDecyphered message: ", decyphered, "\n\n")

and trying to access ffib[fib] returns nil. So trying to message:sub(ffib[i]... later throws an error. When I try accessing ffib's values manually, ffib[1] for example, it works alright, it's only when trying to access it with an iterator that it screws up.

Somewhere else in my code I have this:

io.write("\nPlease provide the message to be cyphered: ")
message = io.read()
cyphered = ""
seq = #message
ffib = {}
a = 0
b = 1
c = a + b
for fib = 1,seq do
    ffib[fib] = c
    a = b
    b = c
    c = a + b
end

which is basically the same thing but instead of using a while loop, it uses a for loop, and it works just fine!

Please help me solve this I am going insane.

lua


Solution 1:[1]

Alright, I figured it out!

io.write("\nPlease provide the message to be decyphered: ")
message = io.read()
seq = #message
ffib = {}
a = 0
b = 1
c = a + b
fib = 0
while c < (seq - 10) do
    fib = fib + 1
    ffib[fib] = c
    a = b
    b = c
    c = a + b
end
decyphered = ""
for i = 1,seq do <--------------
    decyphered = table.concat{decyphered, message:sub(ffib[i],ffib[i])}
end
io.write("\nDecyphered message: ", decyphered, "\n\n")

I was using the wrong variable in the for loop, so it was looping through the entire message length instead of the fibonacci array length, the "nil" values were indexes out of bounds!

To correct this, I simply changed seq for #ffib in that For Loop, marked by an arrow.

Thanks everyone who tried to help me anyway!

Solution 2:[2]

this part doesn't make much sense I think

while c < (seq - 10) do

Why the minus 10? ffib will have less entries than seq while in the loop after that you expect a value in ffib from 1 to seq

And even if you change it to

while c < seq do

Then there still won't be enough for messages larger than length 2.

If anything, you might want to do

while c < (seq + 10) do

But even there you will run into an issue when the message is a certain length.

I'm also not familiar with that algorithm, but it looks pretty weird to me and I wonder what it actually establishes

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SSudor
Solution 2