【问题标题】:Redirecting/redefining print() for embedded Lua为嵌入式 Lua 重定向/重新定义 print()
【发布时间】:2011-05-29 07:56:55
【问题描述】:

我在我的 C++ 应用程序中嵌入了 Lua。我想重定向打印语句(或者可能只是重新定义打印函数?),以便我可以在其他地方显示评估的表达式。

最好的方法是什么:重定向或重新定义 print() 函数?

任何显示如何执行此操作的 sn-ps/指向 sn-ps 的指针将不胜感激。

【问题讨论】:

    标签: c++ c lua


    【解决方案1】:

    参见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),但会处理 printio.write 而无需重新定义。

    【讨论】:

    • 这似乎建议直接修改 Lua 源(我可能错了)——但肯定有更好的方法吗?
    • 好吧,只要不改变任何东西的语义,我对编辑 Lua 源代码并没有特别的反感。我编写了一个 Lua “编译器”,它将文件作为资源绑定到 EXE 中,然后挂钩 Lua 的文件例程以从可执行资源而不是文件系统中读取。只需要更改几行源代码。无法想象如果我试图避免做出这些改变,那将是一场多么可怕的噩梦。
    • Mike M 给出的解决方案不涉及 Lua 代码。您提供自定义打印功能并通过 Lua C 函数lua_register(L,"print", my_print) 注册来覆盖默认打印功能。
    【解决方案2】:

    编写自己的 C 或 Lua 函数并重新定义 print

    【讨论】:

      【解决方案3】:

      您可以简单地从 Lua 脚本重新定义打印。

      local oldprint = print
      print = function(...)
          oldprint("In ur print!");
          oldprint(...);
      end
      

      【讨论】:

        【解决方案4】:

        您可以在 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"' 包含您的文件

        【讨论】:

        • @MikeM。有没有办法使用它来调用luaL_dostring,只需将所需的输出作为char*返回?
        • +1!正是我需要的@ewok,luaL_dostring 返回一个 const char * 所以你有你所需要的。
        • 我应该在luaopen_luamylib()函数中返回什么?
        • 请看我的另一个问题:stackoverflow.com/q/52127154/5224286
        【解决方案5】:

        您只需重新定义以下宏:

        lua_writestring
        lua_writeline
        lua_writestringerror
        

        任何你喜欢的。 我不确定引入它的 lua 版本 - 但它适用于我的 5.3。

        检查您的 lauxlib.h 或 luaconf.h。

        【讨论】:

        • 一般情况下是不够的,io.write() 还是会写到stdout。
        猜你喜欢
        • 2011-09-16
        • 2012-07-09
        • 2012-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-01
        相关资源
        最近更新 更多