lua-users home
lua-l archive

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


> With the introduction of coroutines to Lua, the section of the manual
> dealing with the "for" statement needs to be cleaned up.

Well, obviously I agree. :-)

But given the distraction my main point was ignored: with a little
syntactic sugar, Lua's first-class anonymous functions would be more
"usable."

I've modified my copy of Lua 5 with the following:

 * "iterator x( a, b ) ..." is exactly syntactic sugar for "function ( a,
b, yield ) ...".
 * "begin ( v ) ..." is exactly syntactic sugar for "function ( v ) ...".
 * a "begin ..." following a function call is automatically added as a
parameter to the preceding call.

With those changes I can now do things like this:

  Table{ "a", "b", "c" }:filter() begin ( v )
    if v >= "b" then return true end
  end

  io.withOutputTo ( "somefile.txt" ) begin ()
    io.write( "some text" )
    io.write( "some more text" )
    io.write( "some text" )
  end

with implementations like this:

  iterator table.filter( t )
    local result = {}
    table.foreach( t ) begin (i, v)
      if yield( v ) then
        table.insert( t, v )
      end
    end
    return result
  end

  iterator io.withOutputTo( f )
    io.output( f )
    yield()
    io.output()
  end

The changes I made work independently. For example, if you look at the
"filter" implementation you'll see that it uses the existing
"table.foreach" function--even though it wasn't defined as an "iterator."
My changes simply add the "begin" block as an anonymous function to the
preceding function call. As I said before, it's just syntactic sugar for
things that Lua can already do.

I'll be making a few more changes to make things a bit prettier. For
example, I want parentheses to be optional when there are no arguments. And
I want to find something better than "begin" to mark the block following a
function call...