toit

Break loop from a block in a task


So i have code similar to this i want to run:

main:

  // This works
  mloop :
    print "test"
    return
    
  //This will not compile
  task:: mloop :
     print "test"
     return //this seems t be the problem
    
mloop [block]:
  while true:
    sleep --ms=100
    block.call

I want to break the infinite loop from within the block. But i also need to run the loop in a task. It will not compile and gives the error message Can't explicitly return from within a lambda. This does not seem like it is posible with return or continue. Is there any way a similar funtionality can be implemented?


Solution

  • This is a limitation of the current iteration of the language. You would want to use break.mloop to break out of the loop:

    main:
      task:: mloop:
        print "test"
        break.mloop // Read as "break out of mloop".
    
    mloop [block]:
      while true: ...
    

    However, this functionality isn't implemented in the compiler yet.

    You have a few options to work around this:

    1. Create the lambda that is passed to the task in a function:
    task_function:
      mloop:
        print "test"
        return
    
    main:
      task:: task_function
    

    This always works.

    1. Use the block's return value to signal an exit.
    my_mloop [block]:
      mloop:
        if block.call: return
    
    main:
      task:: my_mloop:
        print "test"
        true  // Signal end.
    

    The latter has the advantage that the block's code would be inside main and could thus share variables more easily. It only works if the mloop function doesn't expect a value from the given block.