【问题标题】:Lua function returning error after false "if statement"Lua 函数在“if 语句”错误后返回错误
【发布时间】:2022-01-27 02:41:48
【问题描述】:

我有一个功能可以将一个点移动到不同的位置。我有一个 positions 表,其中包含每个位置的所有 X 和 Y,位置计数器 (posCounter) 会跟踪点的位置和 maxPos,这几乎是表格 positions 的长度。
在这段代码 sn-p 中,如果 posCounter 变量大于 3,if posCounter <= maxPos then 之后的所有内容都不应运行,但 我仍然收到错误,因为超出了表的限制。

local maxPos = 3
local posCounter = 1
local function movePointToNext( event )
    if posCounter <= maxPos then
        posCounter = posCounter + 1
        transition.to( pointOnMap, { x = positions[posCounter].x, y = positions[posCounter].y } )
    end
end

【问题讨论】:

    标签: lua coronasdk solar2d


    【解决方案1】:
        if posCounter <= maxPos then
            posCounter = posCounter + 1
    

    如果 posCounter == maxPos 会发生什么?你的 if 执行,然后你增加它,所以它太大(等于 maxPos + 1),然后你尝试用它来索引,从而给你一个错误。

    你要么想改变你的 if 停止在 posCounter == maxPos - 1,所以在递增之后它仍然是正确的;或者您想在 索引之后移动增量(取决于代码的预期行为)。

    选项 1

    local maxPos = 3
    local posCounter = 1
    local function movePointToNext( event )
        if posCounter < maxPos then
            posCounter = posCounter + 1
            transition.to( pointOnMap, { 
                x = positions[posCounter].x, 
                y = positions[posCounter].y } )
        end
    end
    

    选项 2

    local maxPos = 3
    local posCounter = 1
    local function movePointToNext( event )
        if posCounter <= maxPos then
            transition.to( pointOnMap, { 
                x = positions[posCounter].x, 
                y = positions[posCounter].y } )
            posCounter = posCounter + 1
        end
    end
    

    【讨论】:

    • 感谢您的回答,现在才意识到这是多么蹩脚的错误。我将使用第一个,因为我仍然需要它移动到下一个,因此需要计数器在移动之前递增。再次感谢。
    猜你喜欢
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 2017-07-20
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多