lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> LUA_FILEHANDLE is a preprocessor definition in lauxlib.h, which is just
> "FILE*"
> 
> So what this means is luaL_checkudata() gets the metatable of the userdata
> object (if it has one), and checks to see that it matches the table
> referenced by the key "FILE*" in the registry table.
> 
> Lua file handles themselves are called luaL_Stream's or just LStream's
> (there's a typedef in liolib.c[2]).
> 
> typedef struct luaL_Stream {
>   FILE *f;  /* stream (NULL for incompletely created streams) */
>   lua_CFunction closef;  /* to close stream (NULL for closed streams) */
> } luaL_Stream;
> 
> ^ found in lauxlib.h[3]
> 
> Lua file handles, in their C form are just ANSI C FILE *'s and a pointer to
> the function to close them (io_fclose() in liolib.c[4]).
> 
> To create a Lua file handle you would need to call newfile() in
> liolib.c[5], but this function is static and therefore not exposed.

You do not need to call newfile. Lua exports everything you need to create
your own files. All you have to do is this:

- call lua_newuserdata(L, sizeof(LStream)) to create a userdata
- set its metatable with luaL_setmetatable(L, LUA_FILEHANDLE)
- set its 'f' to your stream
- set its 'closef' to the function that will close your stream

Everything here (lua_newuserdata, LStream, luaL_setmetatable,
and LUA_FILEHANDLE) is public on purpose. Because LUA_FILEHANDLE and
LStream are public, you can also write your own functions to manipulate
files (and they will work with native Lua files too).

-- Roberto