Q:

C++ and Lua - Unprotected Error (bad callback)? How is this possible

I'm working with LuaJIT's FFI and I'm getting very strange results. This returns a PANIC: Unprotected Error (bad callback):
function idle(ms)
    myDLL.myDLL_idle(session, ms)
end

But this simple print has fixed the problem.
function idle(ms)
    print("anything")
    myDLL.myDLL_idle(session, ms)
end

Another extremely odd solution is to use myDLL.myDLL_idle() inside the main function. How can this even be possible? It's not like I can just do any arbitrary function either if I put the call in a function, the only ones guaranteed to work are a print and sleep.
function idle(ms)
    myDLL.myDLL_idle(session, ms)
end

myDLL.myDLL_idle(session, ms) -- works
idle(ms) -- doesn't work (unless first line of idle() is a print statement)

It's doing the same thing but just in another function. And the print fixing it if I try putting it in a function method just add to the complete weirdness of this. This is a huge problem.

A:

According to the documentation, LuaJIT doesn't allow an FFI-call to be JIT-compiled if the FFI-code calls a C function that calls back into Lua via a stored callback. In most cases LuaJIT will detect those calls and avoid compilation, but if it doesn't, it aborts with the "bad callback" error message. The extra print helped, because it prevented JIT-compilation (print is not compiled atm.).
The proposed solution (instead of calling print) is to explicitly stop the FFI-call from being JIT-compiled using the jit.off function.

