Re: [GD-General] variadic functions
Brought to you by:
vexxed72
From: Thatcher U. <tu...@tu...> - 2003-11-30 16:03:30
|
On Nov 27, 2003 at 10:22 +0800, Brett Bibby wrote: > > I'm trying to bind our scripting engine to our game engine and having > trouble with variadic functions I'm surprised that you have variadic functions on the C/C++ side of your engine. What are they used for? Anyway, one possible approach is to do the wrapping in reverse. I.e. rewrite those functions avoiding the C/C++ implementation of variadic parameters, and instead use your scripting language's parameter-passing mechanism. Bind the functions directly to your scripting language. Provide wrappers for calling them from C/C++. E.g. let's say you're using Lua, and you have an add() function that takes an arbitrary number of doubles and returns their sum: double add(int arg_count, ...) { /* ... */ } You can implement that using the va_ macros, but instead of doing that, you could implement it using the Lua API: int add_lua(lua_State* L) { int arg_count = (int) luaL_checknumber(1); double sum = 0; for (int i = 0; i < arg_count; i++) { sum += luaL_checknumber(2 + i); } lua_pushnumber(L, sum); return 1; } // Wrapper for calling from C++. double add(int arg_count, ...) { // Seat of the pants code, probably incorrect! lua_pushnumber(L, arg_count); va_list argp; va_start(argp, arg_count); for (int i = 0; i < arg_count; i++) { lua_pushnumber(L, va_arg(argp, double)); } va_end(argp) add_lua(L); double result = luaL_tonumber(L, -1); lua_pop(arg_count + 2); return result; } // etc. -- Thatcher Ulrich http://tulrich.com |