c++ - 使用默认打印行为在 C++ 中重新路由 Lua 打印

标签 c++ printing lua

我正在使用 this question 的答案将 lua 的 print 重定向到字符串流。我的功能代码如下。

我的问题是代码并不总是与 lua 自己打印的内容相匹配。最值得注意的是,当我尝试打印函数时,我只是得到函数,而不是函数和地址。示例:

> --in lua
> print(os.exit)
function: 0xabcdef01

> --in my interpreter
> print(os.exit)
function

显而易见的解决方案是在写入luaout之前强制我的自定义打印函数调用lua的tostring(就像默认打印一样)。但是,我真的不知道如何使这项工作有效。如果有人能帮助我,我将非常感激。

这是我的自定义打印:

static int l_my_print(lua_State* L) {
    int nargs = lua_gettop(L);

    for (int i=1; i <= nargs; i++) {
        int t = lua_type(L, i);
        switch (t) {
            case LUA_TSTRING: { /* strings */
                luaout << lua_tostring(L, i);
                break;
            }
            case LUA_TBOOLEAN: { /* booleans */
                luaout << (lua_toboolean(L, i) ? "true" : "false");
                break;
            }
            case LUA_TNUMBER: { /* numbers */
                luaout << lua_tonumber(L, i);
                break;
            }
            default: { /* other values */
                luaout << lua_typename(L, t);
                break;
            }
        }
        if (i!=nargs){
            luaout << "\t";
        }
    }
    luaout << endl;

    return 0;
}

最佳答案

你可以尝试默认这个:

lua_pushfstring(L, "%s: %p", luaL_typename(L, i), lua_topointer(L, i));

 luaout << luaL_typename(L, i) << ": " << lua_topointer(L, i);

这将添加函数的名称和指针。

你可以从C++调用lua函数(不保证工作,因为我没有测试它,但它应该除了语法错误)

lua_getglobal(L, "tostring");
lua_pushvalue (L, i);

if (lua_pcall(L, 1, 1, 0) != 0) {
        printf("error running function `%s': %s\n", "tostring", lua_tostring(L, -1));
        return -1;
}
// get result
char *result = luaL_checkstring (L, -1);

关于c++ - 使用默认打印行为在 C++ 中重新路由 Lua 打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12782580/

相关文章:

lua - 解密Lua字节码?

c++ - boost::algorithm::boyer_moore_search 面向对象示例

c++ - Win32 C++ 使用多媒体定时器

c++ - 在打印机上打印(windows平台32位)

c - 打印机模块的ESC/POS命令

ruby-on-rails - 从 Rails 应用程序到 Star Micronics TSP 143U 的 POS 收据打印

c++ - C++中动态数组是如何实现的?

c++ - 为什么 Bing Maps for Visual Studio 2013 C++ 打不开?

python - 是否可以使用 yaml 元数据 block 来扩展 pandoc 语法?

haskell - 让一个简单的 Haskell HsLua 示例工作