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 种货币,但与其写 currency1、currency2 等,我想要在几行中使用相同的完全相同的代码,就像数学公式一样,因为如您所见,货币每次上涨 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 种货币并浪费资源入侵。
您有多个语法错误:
- 您需要
end
嵌套if
(第 8 行的if
由第 10 行的end
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
使用循环查找匹配的货币。将该货币存储在变量中。使用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