lua-users home
lua-l archive

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


Named parameters in Lua are traditionally simulated via the table
constructor syntax, but the memory allocations make this approach
slower than positional parameters--by a lot in Lua and by orders of
magnitude in LuaJIT.  Example:

  function sum(t) return (t.x or 0) + (t.y or 0) + (t.z or 0) end
  local s = 0
  for i=1,1e8 do
    s = s + sum {z=3*i, y=2*i, i} -- warning: allocs in loop
  end

A more static named parameter resolution would improve this, but it
need not be completely static.  As a compromise, this:

  sum(z=3*i, y=2*i, i)

could be syntactic sugar for something like this:

  sum['z,y'](3*i, 2*i, i)
  sum('z,y', 3*i, 2*i, i) -- or perhaps this

Then, for example, the __index metamethod on the first `sum` table
could build and return a permutation function like this:

  function(z,y,x) return _sum(x,y,z) end

and __index may also memoize, making this really fast and easily
JIT'able if only a few combinations/permutations of the named
parameters are used, as is typically the case.

The key feature of this proposal is that the names and order of the
named parameter keys (i.e. the signature) are formed into a single
string at compile time, while the behavior at runtime can be
dynamically constructed, memoized, and quickly dispatched using this
(interned) signature string as a table key.  Flexibility and
efficiency are both maintained.  The syntactic sugar for method calls
(":") bears some resemblance.