lua-users home
lua-l archive

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


On Mon Feb 17 12:39:17 GMT 2020, Jerome Vuarand <jerome.vuarand at gmail.com> wrote:
> >               NSTimeInterval interval = (lua_type(L, 1) == LUA_TNUMBER) ? 0.001 : lua_tonumber(L, 1) ;
>
> Isn't there a bug in the line above? Or is the ternary operator in
> this language different than in C?

Good catch, no wonder I was seeing so little variance in my tests with different delays. Also changing the default to 10 ^ -6.

> This is not very clear to me (is it to you?). The key question is
> whether the timer callbacks can only be called from
> nextEventMatchingMask, on that same thread, or if the timer callbacks
> are asynchronous. It is fine to have "recursive" lua_pcall-s, ie.
> pcall function x, and have x pcall function y. But you cannot pcall
> function x from thread 1, and pcall function y from thread 2 at the
> same time.

I guess I didn't explain things very well...

First, to be clear, Hammerspoon is runnng lua in a single thread -- the main thread of the application.
(A few long running things that are hadnled solely within Objective-C may run in other threads, but 
upon completion, they send a notification to the event queue of the main thread which is picked up by
`nextEventMatchingMask:NSAnyEventMask` and thus triggers a lua_pcall to a callback function we've
defined earlier.)

So, (ignoring my new function for the moment) what happens on the main application thread is that either
the main thread is sitting idle waiting for events from the application gui or OS in
`nextEventMatchingMask:NSAnyEventMask`, or it's executing lua code by pushing a function reference onto
the stack and then invoking the function with `lua_pcall`. While lua code is being interpreted, events
to the main thread just queue, they can't be acted upon.



So maybe a better visual for what I think this function adds:

wait for new event from `nextEventMatchingMask:NSAnyEventMask` {
    lua_pcall to user function for event type pulled from queue
        ...lua code interpretted here...
        hs_yield() {
            check `nextEventMatchingMask:NSAnyEventMask` for new event and if found {
                lua_pcall to user function for new event type pulled from queue
                    ...lua code interpretted here...
                        (possibly additional yield/pcall combos, but allways in a stack formation)
                    ...lua code interpretted here...
                end
            }
        }
        ...lua code interpretted here...
    end
} (application thread back to idle, go back to waiting for new event)


And described this way, I think I do see that we're essentially just calling a function from
within a function, in C, rather than lua.

--
Aaron