从 C API 获得 Lua 的标准输出

我正在努力从 C 后端中的 Lua 脚本前端获取标准输出:

> type(_ENV.io.stdout) > userdata

从 C 中,我正在做如下操作:

lua_getglobal(L,"_G");
lua_pushstring( L, "io" );
lua_gettable( L, -2 );
lua_pushstring( L, "stdout" );
lua_gettable( L, -2 );
stackTrace( L );

所以此时我得到:

---- Begin Stack ----
Stack size: 3

3 -- (-1) ---- userdata
2 -- (-2) ---- table
1 -- (-3) ---- table
---- End S tack ----

有没有人知道如何从 Lua C API 中获取 stdout,stderr,以便可以对其进行 printf()?

点赞
用户1944004
用户1944004

你可以使用 Lua API 来获取底层文件句柄,但这明显不是一个好主意,因为这是一个实现细节。正如你所看到的,在 Lua 5.2 和 5.1 之间这种方式已经发生了变化。

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

int main() {
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    lua_getglobal(L, "io");
    lua_pushstring(L, "stdout");
    lua_gettable(L, -2);
    FILE *lstdout =
#if LUA_VERSION_NUM > 501
        ((luaL_Stream *)lua_touserdata(L, -1))->f;
#else
        *(FILE **)lua_touserdata(L, -1);
#endif
    lua_pop(L, 2);

    fprintf(lstdout, "Hello World!\n");

    lua_close(L);
}
2018-12-11 07:02:06