为什么 "array[index]" return "nil"?

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

这个问题看似很简单,但是我找不到解决办法,其实我也不知道哪里出了问题!!!

所以基本上我有这个 Lua 代码:

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")

并尝试访问 ffib[fib] returns nil。因此稍后尝试 message:sub(ffib[i]... 会引发错误。 当我尝试手动访问 ffib 的值时,例如 ffib[1],它工作正常,只有在尝试使用它搞砸的迭代器访问它时。

在我的代码的其他地方我有这个:

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

这基本上是同一件事,但它没有使用 while 循环,而是使用 for 循环,而且工作得很好!

请帮我解决这个问题,我快疯了。

这部分我觉得没什么意义

while c < (seq - 10) do

为什么是负 10? ffib 将比 seq 的条目少,而在此之后的循环中,您期望 ffib 中的值从 1 到 seq

即使你把它改成

while c < seq do

那么对于长度大于 2 的消息,仍然不够。

如果有的话,你可能想做

while c < (seq + 10) do

但是当消息达到一定长度时,您仍然会 运行 遇到问题。

我也不熟悉那个算法,但我觉得它很奇怪,我想知道它到底建立了什么

好的,我明白了!

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")

我在 for 循环中使用了错误的变量,因此它循环遍历了整个消息长度而不是斐波那契数组长度,“nil”值是超出范围的索引!

为了更正这个问题,我只是在那个 For 循环中将 seq 更改为 #ffib,用箭头标记。

感谢所有试图帮助我的人!