【问题标题】:Lua clear memoryLua清除内存
【发布时间】:2016-01-14 21:57:12
【问题描述】:

我在 Lua 中制作了一个简单的数字破解程序,但遇到了“堆栈溢出”错误(哦,具有讽刺意味)。我不是 100% 这个错误实际上是什么,因为当我用谷歌搜索时,我得到的只是这个我已经使用了一段时间的网站。我想有办法清除lua文件中的内存。这个程序运行数字非常快,它最多可以运行这些数字 2147483647 次,所以我假设这是一个内存问题。那么有没有办法在运行脚本的同时清除 lua 脚本中的内存?这是我的代码:

num = 0
rand = math.random(2147483647)
function Main()
    print ("Please enter your number(0 - 2147483647)")
    ui = io.read("*number")
    loop()
end
function loop()
    if rand > ui and rand ~= ui then
        rand = math.random(0, ui)
        num = num + 1
        print(rand)
    end
    if rand < ui and rand ~= ui then
        rand = math.random(ui, 2147483647)
        num = num + 1
        print(rand)
    end
    if ui ~= rand then
        loop()
    end
    if ui == rand then
        print("Number Cracked - " ..ui)
        print("It Took " ..num .." Trys To Crack Your Number")
        done = io.read()
    end
end
Main()

编辑

感谢@Marc B 和@Blaatz0r 对答案的评论,我多次调用loop() 并导致“堆栈溢出”,我用while 循环替换它,感谢@Marc B为此,这是我的新代码:

num = 0
rand = math.random(2147483647)
function Main()
print ("Please enter your number(0 - 2147483647)")
ui = io.read("*number")
while( ui ~= rand) do
if rand > ui and rand ~= ui then
rand = math.random(0, ui)
num = num + 1
print(rand)
end
if rand < ui and rand ~= ui then
rand = math.random(ui, 2147483647)
num = num + 1
print(rand)
end
if ui == rand then
print("Number Cracked - " ..ui)
print("It Took " ..num .." Trys To Crack Your Number")
done = io.read()
end
end
end
Main()

【问题讨论】:

  • 你只是一遍又一遍地调用 loop() ......最终你会溢出你的堆栈。为什么必须首先递归? while 循环不是更有效吗?
  • 它一直在调用loop()。因此,所有这些调用都设置到堆栈中。及时溢出。因此堆栈溢出。您应该尝试查找有关堆栈与堆的一些信息。 stackoverflow.com/q/79923/3966890.
  • 谢谢你们两个:D 我的代码工作正常,现在我可以盯着数字滚动一整天,谢谢:D
  • 请注意,您不必将整个代码重写为 while 循环来解决问题。 Lua 有适当的尾调用 (lua.org/manual/5.3/manual.html#3.4.10),因此您可以将对 loop() 的递归调用替换为 return loop()
  • 我觉得这里的标题有点误导

标签: memory lua


【解决方案1】:

感谢@Marc B 和@Blaatz0r 对答案的评论,我多次调用loop() 并导致“堆栈溢出”,我用while 循环替换它,感谢@Marc B为此,这是我的新代码:

num = 0
rand = math.random(2147483647)
function Main()
    print ("Please enter your number(0 - 2147483647)")
    ui = io.read("*number")
    while( ui ~= rand) do
        if rand > ui and rand ~= ui then
            rand = math.random(0, ui)
            num = num + 1
            print(rand)
        end
        if rand < ui and rand ~= ui then
            rand = math.random(ui, 2147483647)
            num = num + 1
            print(rand)
        end
        if ui == rand then
            print("Number Cracked - " ..ui)
            print("It Took " ..num .." Trys To Crack Your Number")
            done = io.read()
        end
    end
end
Main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 2010-12-20
    • 2014-01-13
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多