我有一个运行嵌入式 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/