This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
jv110's profile picture

goto statement support

Started by jv110, 12 October 2016 - 12:34 AM
jv110 #1
Posted 12 October 2016 - 02:34 AM
Recently, I've been suffering a lot with the lack of continue statements in Lua. I searched a bit, and found that Lua 5.2 added goto, which can be used to approximate continue (and greatly simplify the code):

for i, v in ipairs(something) do
  if some_action then
	do_stuff
  else -- Failed; next item
	goto continue
  end
  other_stuff
  ::continue::
end
So, went to test it and… nope. Just like the safe part of the debug lib. And others.
Before those not-even-gonna-say guys say something stupid and the topic is locked, yes, this is useful. For example, I want to skip the current iteration of the loop, without stopping it or filling my program with ugly if statements. (That's the very definition of the continue keyword.) See:

for i, v in ipairs(lines_of_code) do
  if test_for_command then
    for stuff in list_of_stuff do
      if can_do_with current_thing then
        do
        -- what do I do now? I wanna stop!!!! I already did everything!
    els.. i mean end
    -- You can't else a for loop!
      do_it_another_way
    end
  end
  other_actions
end

A solution is to, as I said, fill the program with ugly ifs:

for i, v in ipairs(lines_of_code) do
  local failed = true
  if test_for_command then
    for stuff in list_of_stuff do
      if can_do_with current_thing then
        do
        failed = false
        break
      end
    end

    if failed then
      do_it_another_way
    end
    -- Etc.
  end
  other_actions
end
This really gets in the way when the program gets big.
Lyqyd #2
Posted 12 October 2016 - 03:35 AM
ComputerCraft currently uses Lua 5.1 with some (relatively easy to implement) features of 5.2 added on. Goto won't make an appearance until the swap to 5.2 actually happens. Yes, goto is useful in some instances, but it's also easy to abuse. I'd wager that the vast majority of its use if added will be in situations that would be better handled by other flow control mechanisms that we already have.