[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Exit one Lua state from a (C) API function
- From: Gé Weijers <ge@...>
- Date: Thu, 25 Feb 2021 13:34:49 -0800
I need to create a Lua API function to close/exit a Lua state
from a Lua script.I could try to build some setjmp/longjmp code around it, but
I’m wondering if there might be some built-in feature, e.g., some Lua error/exceptions
that can only be handled in C but not in Lua? In my case, I will call "lua_close" immediately after and I don't need to resume any operation in this state. But for curiosity, is there a way to keep the state "fully operational" after such an operation?
I think you're on the right track, I would define a function that first calls lua_close to release all the resources used by the state and the state itself, and then uses a longjmp to unwind the stack. I would unwind the stack AFTER calling lua_close. lua_close will free the lua_State object, so you'll have to create a new one.
The alternative would be to mess with the internals of the interpreter, which is likely to break when updating to a new version. One problem you have is that the pcall mechanism builds a linked list of "struct lua_longjmp" objects in the C runtime stack (see luaD_rawrunprotected in ldo.c), and if you longjmp around that code this list will not be unwound, so reusing the state is going to require some cleanup. I'm sure there's more.
Depending on your needs you could start your code in a coroutine, and use a coroutine yield from this coroutine to signal your code's exit. You can then use lua_resetthread to clean up the coroutine and reuse the state.