Skip to content
Philipp Janda edited this page Sep 23, 2017 · 2 revisions

luaL_Stream

Lua 5.2 introduced a public definition of the contents of a file userdata (Use LUA_FILEHANDLE to e.g. luaL_checkudata). In Lua 5.2 and 5.3, luaL_Stream contains two members, f which is the FILE* and closef which is a function pointer to a function that should be used to close this FILE*.

In PUC-Rio Lua 5.1, the file userdata simply contains a FILE*, the choice of function to close the FILE* is done via function environments. LuaJIT has it's own different struct, however the first member is a FILE*.

lua-compat-5.3's luaL_Stream definition when used with Lua 5.1 contains just a FILE*. This works with both PUC-Rio Lua 5.1 and LuaJIT. The closef member is not defined with the intention that any user of it will get a compile-time error. Creating new custom file handles is impossible in LuaJIT, and requires vastly different code between Lua 5.1 and newer PUC-Rio Lua versions, so this typedef can't help you there.

example usage:

void dosomething(FILE*, int);

int myfunction(lua_State* L) {
    luaL_Stream *fh = luaL_checkudata(L, 1, LUA_FILEHANDLE);
    int i = luaL_checkinteger(L, 2);
    if (fh->f == NULL
#if LUA_VERSION_NUM > 501
        || fh->closef == 0
#endif
       ) {
        return luaL_argerror(L, 1, "closed file");
    }
    dosomething(fh->f, i);
    return 0;
}
Clone this wiki locally