Lua Loop - 有什么建议吗?

时间:2014-05-20 11:22:53

标签: lua

有人能就这段代码给我一些建议吗?我无法做到这一点,以便当用户结束计算时,如果他输入" y"则重复该过程。有人可以帮忙吗?

if choice == "2" then
    repeat os.execute( "cls" )
    print "How many numbers?"
    amountNo = io.read "*n"
end
if amountNo <= 2 then
    print "You can't have less than 2 numbers."
elseif amountNo >= 14 then
    print "Can't calculate more than 14 numbers."
else
    local sum = 0
    for i = 1, amountNo do
        print( ('Enter number %s'):format(i) )
        local nmb = io.read '*n'
        sum = sum + nmb / amountNo
    end
    print( (' The sum is: %s'):format(sum) )
    print(" Do you want to repeat the calculation? Y/N ?")
    yesno = io.read()
    yesno_input = true or false
    if yesno == "y" or "Y" or "yes" or "Yes" then yesno = true 
    if yesno == "n" or "N" or "no" or "No" then yesno = false
    until yesno==false

end

端 恩德雷

1 个答案:

答案 0 :(得分:0)

如果你想重复整个过程,整个过程必须放在循环中,显然:

repeat
  -- do stuff

  doAgain = io.read()
until doAgain:lower():sub(1,1) == "n"

我用更简单的东西替换了你的支票; :lower()将用户回答转换为小写,:sub(1,1)从中提取第一个字符。如果您认为它过于复杂,请将其打包成函数。

function isNegativeResponse(response) 
   return response:lower():sub(1,1) == "n"
end

repeat
  -- stuff
until isNegativeResponse(io.read())

这看起来很自然,不是吗? 在内部重复代码(填充),直到用户产生否定回复。