【问题标题】:Basic Lua problem - A if statement nested in for loop基本 Lua 问题 - 嵌套在 for 循环中的 if 语句
【发布时间】:2018-09-20 14:40:02
【问题描述】:

我是Lua的业余爱好者,我写了这段代码但编译失败,我检查了语法结构,发现它是匹配的,所以我真的不知道哪里出了问题,它说 18: 预计在“startFishing”附近出现“结束”(在第 16 行关闭“如果”) 但我为什么要那样做?????? BTW startFishing 是我之前在同一个文件中定义的另一个函数。

function detectSuccess()
    local count = 0;
    for x = 448, 1140, 140 do
        color = getColor(x, 170);
        if color == 0xffffff then 
            return false
            startFishing()
        else
            return true
        end
    end
end

【问题讨论】:

  • startFishing()return之后??

标签: lua


【解决方案1】:

正确格式化代码我们有....

function detectSuccess()
   local count = 0;
    for x = 448, 1140, 140 do
        color = getColor(x, 170);
        if color == 0xffffff then 
            return false
            startFishing()
        else
            return true
        end
    end
end

detectSuccess()

startFishing() 语句悬空。从语法上讲,return 之后唯一可以出现的是 else 或 end。

这是来自 lua 解析器的抱怨。

来自lua : programming in lua 4.4

出于语法原因,break 或 return 只能作为块的最后一条语句出现(换句话说,作为块中的最后一条语句,或者就在 end、else 或 until 之前)。

如果要调用startFishing,则需要在返回之前。例如

function detectSuccess()
   local count = 0;
    for x = 448, 1140, 140 do
        color = getColor(x, 170);
        if color == 0xffffff then 
            startFishing() -- moved before the return
            return false
        else
            return true
        end
    end
end

【讨论】:

    【解决方案2】:

    return 之后的同一块中不能有语句。我猜你的意思是这样的:

    if color == 0xffffff then 
       startFishing()
       return false
    else
       return true
    end
    

    缩进你的代码将帮助你发现语法问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-02
      相关资源
      最近更新 更多