Re: C Function with variable number of parameters

Chris Byrne <[email protected]>
Newsgroups gmane.comp.lang.lua.bind.user
Message-ID <[email protected]>
On Thu, Jul 29, 2010 at 7:26 AM, Jason McKesson <[email protected]> wrote:
> Luabind encapsulates all of its function calls in try blocks, and
> catches all exceptions and converts them into lua_errors.
>
> Thus, going back to the question: how do you register a multi-variate
> function through Luabind?

I don't believe this is currently possible. At least not with Luabind directly.

Luabind verifies all the arguments being passed to your function
before calling it. Looking at the number of arguments, their types,
determining the appropriate overload to call, and converting arguments
where possible. I'm not aware of any binding policy that bypasses this
mechanism.

We use lua_register to bind our rare variadic functions, then take
care to catch all exceptions and convert them to an appropriate
lua_error call. This is pretty much what luabind itself does for bound
functions that it calls.

from make_function.hpp:

# ifndef LUABIND_NO_EXCEPTIONS
          try
          {
              results = invoke(
                  L, *impl, ctx, impl->f, Signature(), impl->policies);
          }
          catch (...)
          {
              handle_exception_aux(L);
              lua_error(L);
          }
# else


An alternative (which we actually prefer) is to accept one argument as
a table. This table can then be iterated or indexed as needed by the
called function. Allowing for named parameters etc.

// declare
void my_func( const luabind::object& obj ) {
    if ( LUA_TTABLE != luabind::type(obj) ) throw "Expected table
my_func{ args }";
    // ...
}

// bind
.def( "my_func",	&my_func )

-- use
my_func{ bar=2, foo="string" }

my_func{ 4, 3, 2, 1, "bacon" }


- CB

------------------------------------------------------------------------------
The Palm PDK Hot Apps Program offers developers who use the
Plug-In Development Kit to bring their C/C++ apps to Palm for a share
of $1 Million in cash or HP Products. Visit us here for more details:
http://p.sf.net/sfu/dev2dev-palm
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.