2

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.

1 Answer 1

3

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:

int test(lua_State *l)
{
  int result = 0;
  int nargs = lua_gettop(l);
  for(int i=1; i<=nargs; ++i)
  {
    result += lua_tointeger(l, i);;
  }

  lua_pushnumber(l, result);
  return 1;
}

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.

Sign up to request clarification or add additional context in comments.

2 Comments

val is not declared and is not really needed.
@lhf agreed. I've removed it. In general though, for that kind of issue you're welcome to fix the code (if you have high enough reputation.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.