I am writing a Lua application, and I am trying to access the values of the S_IWUSR
constant inside the stat.h
header file using the FFI library of LuaJIT.
How can I include stat.h
in my Lua code so I can access the constant?
Thanks
With ffi.cdef
you can load most C code in the FFI C namespace, but there's no preprocessor so far, so you should use enums for constant values.
In my sys/stat.h
S_IWUSR
is defined as followed:
#define _S_IWRITE 0x0080
...
#define _S_IWUSR _S_IWRITE
...
#define S_IWUSR _S_IWUSR
Example with LuaJIT:
local ffi = require("ffi")
ffi.cdef([[
enum{S_IWUSR = 0x0080};
]])
print(ffi.C.S_IWUSR) -- 128
There's also the way with static const
variables to add a type.
static const int S_IWUSR = 0x0080;
BUT you have to care not to redefine! Remember: there's just one FFI instance per Lua state, require("ffi")
doesn't make a new one. It's recommend to put C definitions in a module and let the Lua package system manage loading them just once.