lua-users home
lua-l archive

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


On Mon, Jun 1, 2009 at 12:04 PM, Lloyd <lloyd@cdactvm.in> wrote:
>
> Hi,
>
> I would like to know the following kind of thing is possible with Lua. I am
> trying to implement a simple event driven system. Lets start with a sample
>
> --My script
> Event1(MyEventHandler1)
> Event2(MyEventHandler2)
>
> function MyEventHandler1(EventObj obj)
> --some action mechanism
> end
>
> function MyEventHandler2(EventObj obj)
> --some action mechanism
> end
>
> The above may not be a working Lua script, but I am trying to depict my
> idea.
>
> "MyEventHandler1,MyEventHandler2" are two event handler functions which
> receives an event object, which is thrown by the "Event1" or "Event2". There
> will be a function "Event1" implemented in C. I would like to know whether
> there is a mechanism to throw Events from the functions like "Event1" and
> handle it using the above said method.
>
> The above may not be a good solution, is there is any better way for doing
> an event driven program.
>
> Thanks,
>  Lloyd


Hi Lloyd,

In Lua, functions are first-class values, and this means that you can
indeed pass them around as parameters to other functions, etc. Your C
function Event1() would need to put a copy of the function that is
passed to it into a place that it can easily retrieve later through
the API (see the C API functions luaL_ref() and luaL_unref() in the
manual for a ready-made mechanism for this). Once that is done, when
the event has happened and you want to "throw" it to your Lua handler,
you can get this function quickly back again, and call it using
lua_call().

-Duncan