lua-users home
lua-l archive

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


On Jul 7, 2014, at 3:34 AM, Austin Einter <austin.einter@gmail.com> wrote:

> Dear All
> Have a very typical requirement while doing C-Lua interfacing. I am going to explain the problem using below example.
> 
> Say we have three lua functions as below
> 
> lua_f1(arg1)
> lua_f2(arg1, arg2)
> lua_f3(arg1, arg2, arg3)
> 
> Now I want to write a generic C function, that can take lua function name and variable number of arguments and can execute the lua functions and return the return value.
> 
> Below C function can take multiple number of arguments
> int execute_lua_function(char *function_name, int arg1, ...)
> {
>     //get the arguments one by one and push it to stack before we call lua function
> }
> 
> I understand, in C we can write functions with variable number of arguments
> 
> Inside C function, can we find the type of an argument and its values in an iterative way, so that we can push the argument to stack.
> 
> If this can be implemented, then when I want to call lua_f1, I can write code in C as execute_lua_function("lua_f1", arg1), when I want to execute lua_f2, I can write code in C as execute_lua_function("lua_f2", arg1, arg2) and so on....
> 
> 
> Today I achieve it in a different way which is expensive.
> 
> 
> Best Regards
> Austin
> 

The problem here is C, not Lua. The va_arg macros will give you access to the pushed C arguments ONLY if you know the types of those arguments. So either you have to have that knowledge wired-into the function (that is, at compile time), or you have to have some kind of run-time description of them (like printf). In either case, once your C code knows the argument type it is of course trivial to push the appropriate value(s) onto the Lua stack and call the Lua function.

—Tim