重定向/重新定义嵌入式Lua的print()

sky*_*gle 16 c c++ lua

我在我的C++应用程序中嵌入了Lua.我想重定向打印语句(或者只是简单地重新定义打印函数?),这样我就可以在其他地方显示已计算的表达式.

执行此操作的最佳方法是:重定向或重新定义print()函数?

任何显示如何执行此操作的片段/指针将非常感激.

Mik*_* M. 25

您可以在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;
}
Run Code Online (Sandbox Code Playgroud)

然后在全局表中注册它:

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);
}
Run Code Online (Sandbox Code Playgroud)

由于您使用的是C++,因此您需要使用'extern"C"'来包含您的文件.


Pup*_*ppy 10

您只需从Lua脚本重新定义打印即可.

local oldprint = print
print = function(...)
    oldprint("In ur print!");
    oldprint(...);
end
Run Code Online (Sandbox Code Playgroud)


Mud*_*Mud 4

见于.luaB_printlbaselib.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). */
Run Code Online (Sandbox Code Playgroud)

您可以只编辑该函数或定义一个新函数。这样做的优点是简单和便携,但它无法处理io.write(您可能会或可能不关心)。

重定向 IO 不会特定于平台(例如SetStdHandle在 Windows 中),但会处理print并且io.write无需重新定义。