lua-users home
lua-l archive

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

Reuben Thomas wrote:
> > Be careful: to correctly implement tinsert in Lua using the C tinsert you must pass the correct number of parameters to the C
> > function, like in
> >
> > function tinsert(t, n, v)
> >       if (v) then
> >               %tinsert(t, n, v)
> >       else
> >               %tinsert(t, n)
> >       end
> > end
> Sorry, I meant that. The version I posted was an incorrect "optimisation"!

Even that is not correct.  The original tinsert when called with a nil third
argument will insert that nil into the table.  Try:

  x={}  tinsert(x, 1, nil)  print(getn(x))
--> 1

Compatible (fixed) version would be:

  function tinsert(t, ...)
    if arg.n == 1 then
      %tinsert(t, arg[1])
    elseif arg.n == 2 then
      %tinsert(t, arg[1], arg[2])
      error("wronger number of args ("..arg.n+1..") for tinsert");

But that still gives unexpected results for:

  tinsert(t, foo())  --> may generate to tinsert(t,a,b)
  tinsert(t, x, foo())  --> may generate to tinsert(t, x)

when foo does not return the expected number of results.

For a long time I advocate to make C-functions behave similar to
Lua functions regarding argument handling (make missing args nil).
IMHO tinsert has a particularly good example of what can happen...

Ciao, ET.