我在我的 C++ 应用程序中嵌入了 Lua。我想重定向打印语句(或者可能只是重新定义打印函数?),以便我可以在其他地方显示评估的表达式。
最好的方法是什么:重定向或重新定义 print() 函数?
非常感谢任何显示如何执行此操作的片段/指向片段的指针。
最佳答案
您可以在 C 中重新定义打印语句:
static int l_my_print(lua_State* L) {
int nargs = lua_gettop(L);
for (int i=1; i <= nargs; i++) {
if (lua_isstring(L, i)) {
/* Pop the next arg using lua_tostring(L, i) and do your print */
}
else {
/* Do something with non-strings if you like */
}
}
return 0;
}
然后在全局表中注册:
static const struct luaL_Reg printlib [] = {
{"print", l_my_print},
{NULL, NULL} /* end of array */
};
extern int luaopen_luamylib(lua_State *L)
{
lua_getglobal(L, "_G");
// luaL_register(L, NULL, printlib); // for Lua versions < 5.2
luaL_setfuncs(L, printlib, 0); // for Lua versions 5.2 or greater
lua_pop(L, 1);
}
由于您使用的是 C++,因此您需要使用 'extern "C"' 包含您的文件
关于c++ - 为嵌入式 Lua 重定向/重新定义 print(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4508119/