lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Fabien writes:
> [an experiment I did lets you] qualify a loop header with
> additional properties like "if", "while", "until", "for".

That seems closely related to list comprehensions:

  -- List comprehension (proposed syntax
  -- from http://lua-users.org/wiki/PythonLists )
  t = {x*y for x=1,10 for y=1,10 if x+y >= 10}

  -- For loop iterating over that list comprehension
  for _,v in ipairs(t) do u[#u+1] = v end

  -- Fabien's control structure (proposed syntax)
  for x=1,10 for y=1,10 if x+y >= 10 do
    u[#u+1] = x*y
  end

The text "for x=1,10 for y=1,10 if x+y >= 10" is identical.  The main difference
is that you are not building an actual list but rather invoking the code-block
for each element that would exist in such a list.

Another difference is that you add these "while" and "until" clauses for the
purpose of short-circuiting.  I'm not fond of that since that makes these two
seemingly similar constructs behave differently:

  -- Proposed syntax
  for x=1,10 while f() do
    g()
  end

  -- Similar standard syntax (result is quite different!)
  for x=1,10 do while f() do
    g()
  end end

Maybe replace "while/until" with "break if":

  -- Proposed syntax
  for x=1,10 break if not f() do
    g()
  end

  -- Corresponding standard syntax
  for x=1,10 do if not f() then break end
    g()
  end

Now, if we also allow "if not f() then break end" to be re-expressed as "break
if not f()" (as in Perl), then the similarity is even more apparent:

  -- Corresponding standard syntax rewritten with proposed syntax.
  for x=1,10 do break if not f()
    g()
  end

I would recommend list comprehensions support the same syntax:

  t = {x for x=1,10 break if not f()}

The "break if" has the advantage that the break is not nested (more obvious):

  for x=1,10 do
    local y = f()
    break if not y
    g(y)
  end