Re: Proposal for a simple new auxiliary Lua API function

Denis Dos Santos Silva <[email protected]> Tue, 16 Jun 2026 16:53:17 -0700 (PDT)
Newsgroups gmane.comp.lang.lua.general
Message-ID <[email protected]>
https://jdhao.github.io/2022/12/02/lua-variadic-arguments/

Em segunda-feira, 15 de junho de 2026 às 17:12:48 UTC-3, Elemer Pixard 
escreveu:

> When coding a Lua binding to a C/C++ function which requires text
> formatting parameters such as:
>
> void cfunc(p1, p2, fmt, ...);
>
> One simple solution is to use string.format() in Lua
> or coding a Lua wrapper function which does that.
>
> // The binding accepts only the formatted string
> void lua_cfunc(lua_State* L) {
>     // Get p1 and p2
>     const char* fs = luaL_checkstring(L, 3)
>     cfunc(p1, p2, "%s", fs);
>     return 0;
> }
>
> // Call in Lua
> func(p1, p2, string.format(...))
>
> To avoid using or creating this wrapper, the following function could be
> exposed to format a string directly and put the result on the stack:
>
> *int luaL_formatstring(lua_State* L, int index);*
>
> Using this function the binding becomes:
>
> void lua_cfunc(lua_State* L) {
>     // Get p1 and p2
>     luaL_formatstring(L, 3);
>     const char* fs = lua_tostring(L, -1);
>     cfunc(p1, p2, "%s", fs);
>     return 0;
> }
>
> // Call in Lua
> func(p1, p2, fmt, ...)
>
> This new function is basically str_format() from strlib.c with 
> an additional parameter with the index in the stack of the 'fmt' argument.
>
> So str_format() could be changed to:
>
> static int str_format(lua_State* L) {
>     return luaL_formatstring(L, 1);
> }
>
> Please advice if I missed some other simple alternative.
> Thanks and best regards.
>

-- 
You received this message because you are subscribed to the Google Groups "lua-l" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
To view this discussion visit https://groups.google.com/d/msgid/lua-l/b22e8177-5688-4395-9e29-7b52aff79ec9n%40googlegroups.com.