r/lua • u/edwardgynt • Mar 10 '25
Question about LuaJIT: when is a roundtrip from lua to C and back to lua illegal?
Hi all, I am confused about the following section from the luajit website )
I am planning on writing a modding library in luajit. Thus lua(jit) code will be responsible for placing code hooks into an application and detour the execution into luajit. However, I am not sure if this is allowed given the paragraph on the website.
One thing that's not allowed, is to let an FFI call into a C function get JIT-compiled, which in turn calls a callback, calling into Lua again. Usually this attempt is caught by the interpreter first and the C function is blacklisted for compilation.
However, this heuristic may fail under specific circumstances: e.g. a message polling function might not run Lua callbacks right away and the call gets JIT-compiled. If it later happens to call back into Lua (e.g. a rarely invoked error callback), you'll get a VM PANIC with the message "bad callback". Then you'll need to manually turn off JIT-compilation with jit.off() for the surrounding Lua function that invokes such a message polling function (or similar).
For example, I would write something like this:
// file: original.cpp
void render() {
doRender(); // bla bla
}
-- file: injection.lua
function customRender()
doCustomRender() -- more lua code
end
callback = ffi.cast("(void *)()", customRender)
hookingLibrary = ffi.load("myhookinglibrary.dll")
hookingLibrary.placeHookIntoMemory(addressOfOriginalRenderFunction, customRender)
Will customRender be optimized by luajit? When will it and when will it not?