【问题标题】:LUA from if statement to loop with if elseif statementsLUA 从 if 语句到 if elseif 语句循环
【发布时间】:2019-03-10 02:57:03
【问题描述】:
function checkCurrency(checker)
  return (checker % 2 == 0)
end

local currency1 = 105
local currency2 = 110
local currency3 = 115


if(checkCurrency(currency1) == true) then
      print("yes1")
elseif(checkCurrency(currency2) == true) then
      print("yes2")
elseif(checkCurrency(currency3) == true) then
      print("yes3")
else
      print("no currency available")
end

我对代码的想法是循环 100 种货币,但我不想编写货币 1、货币 2 等,我希望在几行中使用类似数学公式的相同的确切代码,因为如您所见,货币上升每次5,所以有一个开始是105,结束应该是500。如果它们都不匹配,它应该在最后抛出一个else语句。

我最初的想法是这样的:

function checkCurrency(checker)
  return (checker % 2 == 0)
end

for i = 105,500,5 
do 
   if(i == 105) then 
       if(checkCurrency(i) == true) then
          print("yes" .. i)
   end
   if(i ~= 105 and i ~= 500) then 
       elseif(checkCurrency(i) == true) then
          print("yes" .. i)
   end
   if(i == 500) then
      print("no currency available")
   end

end

但这不可能,因为它试图结束第二个 if 语句而不是第一个,所以我不知道如何以安全的方式解决这个问题,任何提示或示例都是一个不错的开始。此外,我不想检查每一行,如果它适用于示例 currency5,它应该停止,就像第一个带有 if、elseif 和 end 语句的代码一样。所以不会循环500种货币,白白浪费资源。

【问题讨论】:

    标签: lua


    【解决方案1】:

    您有多个语法错误:

    • 你需要end你的嵌套if(第8行的ifended by line 10的end,在查看列表时你希望它是end外部if
    • 如果您在同一级别没有以前的 if,则不能使用 elseif(第 12 行)

    通用解决方案可能如下所示:

    local valid
    for i=105,500,5
    do
        if(checkCurrency(i)) then
            valid=i
            break
        end
    end
    if (not valid) then 
        print("no currency available")
    else
        print("Found " .. valid)
    end
    

    【讨论】:

      【解决方案2】:

      使用循环查找匹配的货币。将该货币存储在变量中。使用break 退出循环。然后使用if--else 使用该货币开展业务。

      local function checkCurrency(checker)
        return checker % 2 == 0
      end
      
      local currency
      for i = 105, 499, 5 do
        if checkCurrency(i) then
          currency = i
          break
        end
      end
      
      if currency then
        print('yes' .. currency)
      else
        print("no currency available")
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-22
        • 2018-10-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多