How can I know the number of arguments passed to a C function from lua?
Will the following work?
int test(lua_State *l) {
int result = 0;
int n=1;
while(!lua_isnil(l,n)) {
result = result + lua_tointeger(l, n);
++n
}
lua_pushnumber(l, result);
return 1;
}
NOTE: This is essentially a resurrection of a question deleted by its owner that I thought was worth keeping.
All the arguments are just pushed onto to the lua stack,
so you can get the number of elements by finding out the initial size of the stack.
The call to do that is
lua_gettop(L).So your code would look roughly like this:
The problem with the code as originally written is that it will not handle null arguments correctly. e.g
test(1,nil,3)will return 1, rather than 4.