lua-users home
lua-l archive

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

Hey all; new member and lua user here so be patient. :)

I'm a newbie C programmer, a fairly experienced Pythonista, and I'm
getting into Lua. So please tailor your answers or analogies to my

I've been trying to write a C function in order to expose the
posix_fadvise function into Lua, for a specific use-case involving a
device ( that exposes its internal state through a virtual
file on a virtual usb-device. So I *do* have a good reason to disable
disk caching! That'll solve the usual FAQ #1: Don't mess with caching.

What I have looks like this:


static int l_posix_fadvise (lua_State *L) {
  int *validfile, *validstart, *validend, *validadvise;
  int nargs = lua_gettop(L);
  const lua_Integer fileno = lua_tointegerx(L, 1, validfile);
  const lua_Integer start = lua_tointegerx(L, 2, validstart);
  const lua_Integer end = lua_tointegerx(L, 3, validend);
  const lua_Integer advise = lua_tointegerx(L, 4, validadvise);
  if (!(*validfile & *validstart & *validend & *validadvise)) {
    lua_pushstring(L, "Incorrect args: all arguments must be numbers.");
  int result = posix_fadvise((int) fileno, (int) start, (int) end,
(int) advise); lua_pushinteger(L, result);
  return 1;


..this was based on the assumption that file descriptors were always
integers; I'm a C beginner so I've only seen "open" and not "fopen",
which returns a "FILE*" instead.

Problem is, posix_fadvise needs an integer file descriptor, not a FILE*
file descriptor.

I can see from the Lua source that it uses "LStream", and the "f"
property of LStream contains the FILE* returned by fopen?

I also know that if I can access that FILE* item (as a FILE*), then I
can use fileno() to get the file descriptor number, which I can pass to

So, how do I extract the LStream or FILE* data from lua into my C
function? Do I cast a userdata into an LStream like (LStream)
getuserdata? Is there another way to get the file descriptor as an
integer from within lua, so it'll work with my above function without

Thanks in advance,

Attachment: signature.asc
Description: PGP signature