Next: 8.10 Calling Lua Functions Up: 8 Some Examples Previous: 8.8 Modules

8.9 A CFunction

A CFunction to compute the maximum of a variable number of arguments is shown below.
void math_max (void)
{
 int i=1;   /* number of arguments */
 double d, dmax;
 lua_Object o;
 /* the function must get at least one argument */
 if ((o = lua_getparam(i++)) == LUA_NOOBJECT)
   lua_error ("too few arguments to function `max'");
 /* and this argument must be a number */
 if (!lua_isnumber(o))
   lua_error ("incorrect argument to function `max'");
 dmax = lua_getnumber (o);
 /* loops until there is no more arguments */
 while ((o = lua_getparam(i++)) != LUA_NOOBJECT)
 {
  if (!lua_isnumber(o))
    lua_error ("incorrect argument to function `max'");
  d = lua_getnumber (o);
  if (d > dmax) dmax = d;
 }
 /* push the result to be returned */
 lua_pushnumber (dmax);
}
After registered with
lua_register ("max", math_max);
this function is available in Lua, as follows:
i = max(4, 5, 10, -34)  -- i receives 10


Next: 8.10 Calling Lua Functions Up: 8 Some Examples Previous: 8.8 Modules