lua-users home
lua-l archive

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


On Mon, Jun 8, 2009 at 1:52 PM, Wesley Smith<wesley.hoke@gmail.com> wrote:
>> Not so, when being called from lua, always use the L you were passed,
>> until the time that you return to lua, at which time you should assume
>> that L to be invalid.
>
> If you assume the L to be invalid, then how do you manage to send a
> callback that doesn't come from Lua at all, but say from the OS event
> loop, into the lua_State?

L isn't thread safe, so there are no threads involved, right?

If there is only one state created, and its called into from a
windows/QT/... style event loop, then you can just use the L you got
back from lua_newstate().

Otherwise, whatever C code called lua_newstate(), before executing any
lua code, can create a lua global that is a lightuserdata that points
to the global state, so instead of having to go into the opaque lua
state struct to find the global, it gets it as a lua variable. I've
never had to do this, though.

Maybe this won't work for you, but what I try to in those kind of
situations is invert things. I'd write the callback registration
function as pure lua, inserting the lua callback function into a
global table mapping events to callbacks.

>From outside of the lua state, the main app event loop that creates
the lua state would call into lua, and then check the callback table,
for every event it sees, it would register with the OS interest in
that event, and when it gets notification, it would call into lua,
which would have a pure lua dispatch that would look up the
(multiple?) callbacks associated with the event and call them.

It's expensive to call into lua, a bit, so its better that every event
calls into lua once, and it's often better to write dispatch and
callback handling code in lua, anyhow. You can unit test your lua code
from lua, for example, simulating events and messing with event order.

Cheers,
Sam