lua-users home
lua-l archive

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


On Fri, May 6, 2011 at 4:38 PM, Henk Boom <henk@henk.ca> wrote:
> On 6 May 2011 15:30, HyperHacker <hyperhacker@gmail.com> wrote:
> > (...)
> > I've always found vararg support in Lua to be awkward and confusing,
> > with a lot of bugs that can crop up if one of your arguments is nil.

Then don't use #.
See <http://lua-users.org/lists/lua-l/2011-04/msg00013.html>
and <http://lua-users.org/lists/lua-l/2011-04/msg00065.html>
(^ shameless plug).

> > Having to call select() for each argument also seems terribly
> > inefficient.
> > I wonder, can there not just be a table _ARG in each function,
> > containing all arguments to the function? (Maybe only if it uses
> > vararg?) That seems like a far simpler and less error-prone approach.
> > (Though it would have to also have an 'n' field for number of
> > arguments, as using # brings back a lot of those same issues when you
> > have a nil argument...)
>
> Because unlike most of the other approaches, this has the
> GC/allocation overhead of creating a table.
>
> AFAIK in lua 5.2 you can accomplish this functionality with
>
> local _ARG = table.pack(...)
>
>   henk

Just to complement Henk's answer a bit...

>From <http://www.lua.org/manual/5.0/manual.html#2.5.8>:

  When a function is called, the list of arguments is adjusted to the
  length of the list of parameters, unless the function is a variadic
  or vararg function, which is indicated by three dots (`...´) at the
  end of its parameter list. A vararg function does not adjust its
  argument list; instead, it collects all extra arguments into an
  implicit parameter, called arg. The value of arg is a table, with a
  field `n´ that holds the number of extra arguments and with the
  extra arguments at positions 1, 2, ..., n.

>From <http://www.lua.org/manual/5.1/manual.html#7.1>:

  The vararg system changed from the pseudo-argument arg with a table
  with the extra arguments to the vararg expression. (See compile-time
  option LUA_COMPAT_VARARG in luaconf.h.)

Your proposed "_ARG" used to be called "arg".
The standard way to adapt functions that used "arg" to make them run on
Lua 5.0 was to add a line like this to the beginning of each one (IIRC):

  local arg = table.pack(...)

Cheers,
  Eduardo Ochs
  eduardoochs@gmail.com
  http://angg.twu.net/