lua-users home
lua-l archive

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


2010/11/27 Francesco Abbate <francesco.bbt@gmail.com>
> 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 ?

Check out the documentation for the functions luaL_check* and luaL_opt* :

http://www.lua.org/manual/5.1/manual.html#luaL_checkint
http://www.lua.org/manual/5.1/manual.html#luaL_optint

The check* are for required argument : they will raise a friendly
error message if the argument is nil/omitted, or of the wrong type.
The opt* functions return the default value you specify if the
parameter is omitted/nil. Your example function would be written as
follow :

int myfunc(lua_State* L)
{
    const char* s = luaL_checkstring(L, 1);
    int a = luaL_optint(L, 2, 0);
    double b = luaL_optnumber(L, 3, 0.0);
    ....
    return 0;
}

These functions are simple and invaluable. If you need to write
similar functions for your own types (and you should :-), there are
utility functions such as luaL_checktype, luaL_argcheck or
luaL_argerror.

--
Julien Cugnière