【发布时间】:2011-05-29 07:56:55
【问题描述】:
我在我的 C++ 应用程序中嵌入了 Lua。我想重定向打印语句(或者可能只是重新定义打印函数?),以便我可以在其他地方显示评估的表达式。
最好的方法是什么:重定向或重新定义 print() 函数?
任何显示如何执行此操作的 sn-ps/指向 sn-ps 的指针将不胜感激。
【问题讨论】:
我在我的 C++ 应用程序中嵌入了 Lua。我想重定向打印语句(或者可能只是重新定义打印函数?),以便我可以在其他地方显示评估的表达式。
最好的方法是什么:重定向或重新定义 print() 函数?
任何显示如何执行此操作的 sn-ps/指向 sn-ps 的指针将不胜感激。
【问题讨论】:
参见lbaselib.c 中的luaB_print。那里的评论是:
/* 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). */
您可以只编辑该函数或定义一个新函数。这具有简单和可移植的优点,但它无法处理io.write(您可能关心也可能不关心)。
重定向 IO 不会特定于平台(例如 Windows 中的 SetStdHandle),但会处理 print 和 io.write 而无需重新定义。
【讨论】:
lua_register(L,"print", my_print) 注册来覆盖默认打印功能。
编写自己的 C 或 Lua 函数并重新定义 print。
【讨论】:
您可以简单地从 Lua 脚本重新定义打印。
local oldprint = print
print = function(...)
oldprint("In ur print!");
oldprint(...);
end
【讨论】:
您可以在 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"' 包含您的文件
【讨论】:
luaL_dostring,只需将所需的输出作为char*返回?
luaopen_luamylib()函数中返回什么?
您只需重新定义以下宏:
lua_writestring
lua_writeline
lua_writestringerror
任何你喜欢的。 我不确定引入它的 lua 版本 - 但它适用于我的 5.3。
检查您的 lauxlib.h 或 luaconf.h。
【讨论】: