lua-users home
lua-l archive

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


Quoth Francesco Abbate <francesco.bbt@gmail.com>, on 2010-11-27 15:56:51 +0100:
> I have a very basic question about how a Lua C function should check
> optional arguments. Let us suppose a C function with the following
> prototype:
> 
> myfunc (s[, a, b])
> 
> where the two parameters a and b are optional. When the C function is
> called what is the correct way to check for the optional parameters ?
>
> Should I use lua_gettop to know how many parameters was given ? In
> this case can be tricky because you can give explicitly a nil value
> and in this case, even if it is nil, it will count as an additional
> value in the stack.

In other words, you want to accept up to 3 parameters and treat an
explicit nil as though it were absent?

An easy and clean way to do that would be to call lua_settop(L, 3)
near the beginning, adjusting the entire stack (parameter list) to
exactly 3 slots and filling any trailing unspecified slots with nil.

You could also use lua_isnoneornil, but you'd have to be careful about
pushing other things in the meantime and accidentally treating them as
though they were arguments.

See the definition of "acceptable" (within allocated range) versus
"valid" (within range containing actual values) indices in the Lua
manual, section 3.2 "Stack Size".

   ---> Drake Wilson