lua-users home
lua-l archive

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


It was thus said that the Great Russell Haley once stated:
> Hi,
> 
> Given this Lua function:
> 
> function write_log(level, ...)
> local str = string.format(...)
> logger:log(logging.level[level], str)
> end
> 
> 
> Is it possible to pass varargs  from C to Lua like so:
> 
> int wrlog(int level, ...)
> {
> lua_getglobal(L, "write_log");
> <slick code that passes varags goes here>
> lua_call(L, lua_gettop(L)-1, 0);
> }
> 
> 
> I've found this on stack overflow:
> 
> ///Rh - Replaced old call for 5.3 syntax
> //lua_getfield(L, LUA_GLOBALSINDEX, "print");
> lua_getglobal(L, "write_log");
> lua_insert(L, 1);
> lua_call(L, lua_gettop(L)-1, 0);
> 
> But I'm still not getting what I want. I also found call_va from in
> the online 5.2 PIL, but it requires I know how many parameters I am
> passing in and what type they are.  I was also trying to avoid sprintf
> because I'm lazy and want Lua to do all the heavy lifting.

  When I implemented the syslog() wrapper for Lua [1], I do have Lua doing
the heavy lifting, but it's the Lua side that gets the variable arguments,
not C.  Going the other way, I can't really see a way---you *have* to use
the machinery of <stdarg.h>, which involves knowing when to stop reading
parameters (using a count, sentinel value, or some format string), and what
types they are (and knowing the C promotion rules because in a variable
argument function, chars and shorts get promoted to int, floats to double,
size_t to who knows?) in order to extract them.

> Thoughts (other than 'don't be so lazy')?

  Don't ... oh ... um ... no, no other thoughts.

  -spc (Also, use snprintf(), NOT sprintf() as that is dangerous [2])

[1]	https://github.com/spc476/lua-conmanorg/blob/fff20ac845850939943606f3f2d69346f4711be3/src/syslog.c#L256

[2]	It's possible to overflow the buffer using sprintf().