Lua 函数在错误"if statement"后返回错误



我有一个将点移动到不同位置的函数。我有一个位置表,包含每个位置的所有X和Y,一个位置计数器(posCounter(可以跟踪点的位置,还有一个maxPos,这几乎是表的长度
在此代码片段中,如果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
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

最新更新