lua-users home
lua-l archive

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

On Mon, 5 Aug 2002, Luiz Henrique de Figueiredo wrote:

> >How can I pass a lua callback function to a C function and later call this
> >function from C ?
> Sure. You can lua_call anything that's on the stack.
> --lhf

To expand on this answer a little bit, yes you can pass lua functions to
your C program, store them somewhere (global variables or a data
struture or whatever), then call them from your 'C' code using lua_call.

A few notes though (someone please correct me here if I'm wrong, I haven't
done this myself yet):

    The variable type for a lua function is the generic Lua object type

    You'll want to tell the garbage collector that you're keeping a
    reference to the function object, otherwise it might go away. You'll
    have to check the API documentation on how to do this, but if I
    remember correctly it's pretty easy.

    Likewise, you'll have to tell the garbage collector when you stop
    having a reference from 'C' to the function.

    Finally, you'll have to push the function on the stack of a lua
    state before calling it.

Anyone have a code example for this?

  - Tom