moonscript icon indicating copy to clipboard operation
moonscript copied to clipboard

In loops as expressions, ambiguity when returning inner loops.

Open strait opened this issue 6 years ago • 1 comments

For example:

new = for sub in list
    for x in sub
        trans x

At first glace, one sees three possibilities. The documented behavior is that this results in an empty list, since the inner loop is not explicitly returned. However, since items are expected from the outer loop, maybe deference is made to the inner loop returning each value, as in how nested loops are implemented when using multiple for clauses in a list comprehension.

The last possibility is what is currently implemented. The inner loop returns a separate inner list as if the loop had been explicitly returned. However, if I return the inner loop explicitly, erroneous code is generated.

strait avatar Oct 23 '19 00:10 strait

I just tested this and it compiles as I would expect. I can help clarify the docs to make it more clear if you tell me where it's confusing.

Operations that force something to become an expression (like return, or assign) bubble down into blocks, and convert the final statement in that block into a expression. You can see this with the if statement format:

a = if something
  if other
    "hello"
  else
    "world"
else
  2

So in your example, the assignment causes the inner loop to convert to an expression (which means accumulating an array with the results)

leafo avatar Feb 02 '20 19:02 leafo