重定向/重新定义嵌入式Lua的print()
我在我的C ++应用程序中嵌入了Lua。 我想重定向打印语句(或者只是简单地重新定义打印函数?),这样我就可以在其他地方显示已计算的表达式。
执行此操作的最佳方法是:重定向或重新定义print()函数?
任何显示如何执行此操作的片段的片段/指针都将非常感激。
您可以在C中重新定义print语句:
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”'包含您的文件
您只需从Lua脚本重新定义打印即可。
local oldprint = print print = function(...) oldprint("In ur print!"); oldprint(...); end
请参阅luaB_print
中的lbaselib.c
。 那里的评论如下:
/* If you need, you can define your own `print' function, following this model but changing `fputs' to put the strings at a proper place (a console window or a log file, for instance). */
您只需编辑该function或定义一个新function即可。 这具有简单和便携的优点,但它不会处理io.write
(您可能会或可能不关心)。
重定向IO不是特定于平台的(例如Windows中的SetStdHandle
),但是会在不重新定义的情况下处理print
和io.write
。
编写自己的C或Lua函数并重新定义print
。
您可以重新定义以下宏:
lua_writestring lua_writeline lua_writestringerror
无论你喜欢什么。 我不确定引入它的lua版本 – 但它适用于我的5.3。
检查你的lauxlib.h或luaconf.h。