Search code examples
luarobotics

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


So I have a task to be done which is to program the robot (AUBO) to pick different objects and place them in a certain order (Point A, B, C, D). I'm using some vision system known as pim60. So if an object is detected it will go and pick and the rest of the program are waypoints to drop products. The first problem is I want it to go to the next waypoint to drop the and the second thing is, the next drop point cannot be skipped until an object is detected for that drop point.

In my own code, I wrote a rather lengthy program like this.

::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

There is no error and the program runs as expected. However, I'm wondering if there is any better way to do it.


Solution

  • The only generally accepted use-case for goto is error handling, e.g. to jump forward to the cleanup code. But even for that it usually can and should be avoided.

    You can probably do something like this:

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

    Also, if you're repeating the same code three times, you should extract it into a function, and maybe give the position as a parameter. Or at least put the whole thing into a for loop.