lua-users home
lua-l archive

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


nil and argument passing somewhat akward in Lua.

There is a difference between
foo()
and
foo(nil)
and
foo(nil, nil)

Cause the called function can differ with select('#', ...)

There is also a difference betwen
function f() return end

and

function f() return nil end

In your case, I suppose returning nil instead of more nothing than nil
will circumvent your problems.

On Fri, Feb 25, 2011 at 9:22 PM, Hisham <hisham.hm@gmail.com> wrote:
> Hi list,
>
> I bumped into a behavior that surprised me today. I have a function
> that may or may not return a value, and insert that value into a
> table. Given that Lua ignores extra arguments and fills missing
> arguments with nil, I expected that I could just do
>
>   table.insert(my_table, my_function())
>
> But I got "wrong number of arguments to 'insert'". What surprised me
> the most, however, was that while passing a nil variable is allowed,
> passing a nullary function is frowned upon:
>
> Lua 5.1.3  Copyright (C) 1994-2008 Lua.org, PUC-Rio
>> t = {}
>> x = nil
>> table.insert(t, x)
>> f = function() end
>> table.insert(t, f())
> stdin:1: wrong number of arguments to 'insert'
> stack traceback:
>        [C]: in function 'insert'
>        stdin:1: in main chunk
>        [C]: ?
>>
>
> I understand the mechanics of this behavior (one pushes nil to the
> stack as opposed to pushing nothing, as can be demonstrated with
> select()), but I wonder if this extra check in table.insert doesn't go
> somewhat against the general behavior of parameter-passing in Lua
> (where missing arguments are filled with nil), given that nil is a
> valid value for the argument in this function.
>
> -- Hisham
>
>