Lua

The LuaJIT Wiki

not logged in | [Login]

FFI Knowledge

Convert a cdata pointer to Lua number

The canonical way to convert a cdata pointer to a Lua number is:

tonumber(ffi.cast('intptr_t', ffi.cast('void *', ptr)))

This returns a signed result, which is cheaper to handle and turns into a no-op, when JIT-compiled. If you really need an unsigned address (and not just an abstract identifier), then use uintptr_t. Source

Constants

local ffi = require("ffi")
ffi.cdef[[
	struct whatever {
	    static const int FOO = 42;
	    static const int BAR = 99;
	};
	]]
local W = ffi.new("struct whatever")
print(W.FOO, W.BAR)

Yes, these are compiled to actual constants, just like enum constants (and unlike Lua table fields). Except that enum constants are global in C, even if defined inside a struct. Note that it's slightly more efficient to use an instance of the dummy struct (W) as a namespace than using the ctype. Source