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.