lua-users home
lua-l archive

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

Mike Pall wrote:
> Well, there's a reason the FFI doesn't provide for a way to access
> the current lua_State pointer ... what you're doing is not safe.

What's what I suspected.

> - When the FFI call is compiled, the global state is not in sync
>   at all. Calling back into the same Lua state (or any coroutine
>   of it) will lead to weird crashes, GC assertions and so on.
> - When the FFI call is only interpreted, the global state is in
>   sync, but the current Lua thread (coroutine) is not reentrant,
>   i.e. you must not use lua_*call on it. It'll cause more subtle
>   crashes if you violate this rule.

Very interesting. Can it be documented on ffi pages, please?

> OTOH, if you ...
> - Create an extra coroutine and anchor the Lua thread object
>   somewhere
> - *and* run your callback only on the associated lua_State pointer
> - *and* make sure the FFI call to the outer event loop (or whatever)
>   is not compiled,
> ... then this ought to be safe (famous last words).
> To make sure the FFI call to the event loop is not JIT-compiled,
> use for the surrounding Lua function.

Thanks, I'll try it.

> Another option is to call back into a separate Lua VM instance,
> obtained with luaL_newstate() + luaL_openlib(). This is completely
> safe, but you'll need to explicitly pass around code and data.
> See:

Yes, that should be completely safe. I'll give users a safe option but
for testing purposes I'd like to have access to the main state.

Many thanks for the help,