lua-users home
lua-l archive

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


If a function definition has zero arguments, why not allow the
parenthesis to be omitted?

  function test
    print("hello")
  end
  test = function print("hello") end
  lunit.assert_error("problem", function fail(2) end)

Asko Kauppi's "do patch" is an extension of this idea:

  http://lua-users.org/wiki/LuaPowerPatches
  http://lua-users.org/lists/lua-l/2004-09/msg00173.html

I mention this in part because in Perl there is a simple syntax
for anonymous closures that permits user-defined control structures
to be simulated fairly well.  For example, say we want a custom
control structure that executes the given code block three times.
We can do this in Perl:

  # implementation
  sub do_thrice(&) {
    my ($closure) = @_;
    $closure->() for 1..3;
  }

  # example usage
  my $x = 0;
  do_thrice {
    print $x++;
  };

The current way to do that in Lua is

  -- implementation
  function do_thrice(closure)
    for _=1,3 do closure() end
  end

  -- example usage
  local x = 0
  do_thrice(function()
    print(x)
    x = x + 1
  end)

Obviously, the parentheses make that not so elegant.  This would
be near optimal:

  local x = 0
  do_thrice do
    print(x)
    x = x + 1
  end

Simulating control structures with more than one block would
still be a bit cumbersome:

  unless(do x == 5 end, do print("not five") end)

However, a trick one might use is to make "unless" take the first
closure and return a new closure that then evaluates the second
closure.  That's probably not entirely efficient, but it works:

  unless do x == 5 end do print("not five") end

However, one would really want this:

  unless x == 5 then
    print("not five")
  end

but I'm not sure how one would achieve that without some hook
built into the parser.