通常可以在 else 下使用 goto 循环 if 语句吗?

In general is it ok to loop if statements with goto under else?

所以我有一个任务要完成,就是对机器人(AUBO)进行编程,让它拾取不同的物体并将它们按一定的顺序放置(A、B、C、D 点)。 我正在使用一些称为 pim60 的视觉系统。因此,如果检测到一个物体,它会去挑选,程序的其余部分是 waypoints 来丢弃产品。第一个问题是我希望它转到下一个航点以放下,第二个问题是,在检测到该放置点的对象之前不能跳过下一个放置点。

在我自己的代码中,我写了这样一个相当冗长的程序。

::LoopA::
script_common_interface("SICKCamera","takePhoto")
script_common_interface("SICKCamera","getResult")
Located = script_common_interface("SICKCamera","partLocated")
if(Located == 1) then
.
.
.
Drop at position A
else 
goto LoopA
end

::LoopB::
script_common_interface("SICKCamera","takePhoto")
script_common_interface("SICKCamera","getResult")
Located = script_common_interface("SICKCamera","partLocated")
if(Located == 1) then
.
.
.
Drop at position B
else 
goto LoopB
end

::LoopC::
script_common_interface("SICKCamera","takePhoto")
script_common_interface("SICKCamera","getResult")
Located = script_common_interface("SICKCamera","partLocated")
if(Located == 1) then
.
.
.
Drop at position C
else 
goto LoopC
end

::LoopD::
script_common_interface("SICKCamera","takePhoto")
script_common_interface("SICKCamera","getResult")
Located = script_common_interface("SICKCamera","partLocated")
if(Located == 1) then
.
.
.
Drop at position D
else 
goto LoopD
end

没有错误,程序按预期运行。但是,我想知道是否有更好的方法来做到这一点。

goto 唯一普遍接受的 use-case 是错误处理,例如跳转到清理代码。但即便如此,通常也可以而且应该避免。

你或许可以这样做:

-- loop B
repeat
  take photo, etc.
  located = ...
until(located == 1)

Drop at position B

此外,如果您将相同的代码重复三次,则应将其提取到一个函数中,并可能将位置作为参数提供。或者至少把整个事情放到一个 for 循环中。