c - 将 lua 输出发送到非标准输出

标签 c lua stdout

我有一个运行嵌入式 Lua 的 C 程序。截至目前,它只是一个 Hello World 。不过,在继续之前,我希望能够将 lua 输出发送到 stdout 以外的地方,以便我可以以某种方式对其进行操作。这是我的代码:

#include <stdio.h>

#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

int main() {
    lua_State *luaVM = luaL_newstate();
    //char result[1024];

    if (luaVM == NULL) {
        printf("Error initializing lua!\n");
        return -1;
    }
    luaL_openlibs(luaVM);
    luaL_dostring(luaVM, "print(\"hello world!\")");
    //Somehow put the output into result

    //printf("%s\n%s\n", result, result);

    lua_close(luaVM);
    return 0;
}

例如,我想使用注释中看到的result 来打印两次lua 代码的结果。这能做到吗?

最佳答案

如果您的 Lua 代码将使用 print 来输出内容,那么我想最简单的方法是从 Lua 本身重新定义 print。像这样:

print_stdout = print -- in case you need the old behavior

print = function(...)
  for arg,_ in ipairs({...}) do
    -- write arg to any file/stream you want here
  end
end

关于c - 将 lua 输出发送到非标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11885895/

相关文章:

c - 一次通过多个空格替换为单个空格并消除前导和尾随空格

go - 添加/替换/修补标准库

lua - 代码块的脚本语言

c - 搜索二维数组中 2 个数字的乘积

c - 指针定义上的语法错误似乎有效(来自工作库)SDCC

c - 我尝试进行的新系统调用有问题(Ubuntu 18.04.1 LTS 内核 :4. 17.4)

java - eclipse 在标准 StdIn 类中自动交叉函数名称

android - 用于 iOS 和 Android 开发的 Corona vs Titanium

python - 使用 capsys 捕获 stdout 和 stderr

c# - 在修改 Cursor 的代码中重定向标准输出