Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing an executable function pointer?

Tags:

lua

Usually one would only push 'userdata' when the data isn't any of Lua's standard types (number, string, bool, etc).

But how would you push an actually Function pointer to Lua (not as userdata; since userdata is not executable as function in Lua), assuming the function looks like so:

void nothing(const char* stuff)
{
    do_magic_things_with(stuff);
}

The returned value should behave like the returned value from this native Lua function:

function things()
    return function(stuff)
        do_magic_things_with(stuff)
    end
end

Is this possible to do with the C API? If yes, how (Examples would be appreciated)?

EDIT: To add some clarity, The value is supposed to be returned by a function exposed to Lua through the C API.


1 Answers

Use lua_pushcfunction

Examples are included in PiL

Here is an example that follows the form of the currently accepted answer.

#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <stdio.h>

/* this is the C function you want to return */
static void
cfunction(const char *s)
{
    puts(s);
}

/* this is the proxy function that acts like cfunction */
static int
proxy(lua_State *L)
{
    cfunction(luaL_checkstring(L, 1));
    return 0;
}

/* this global function returns "cfunction" to Lua. */
static int
getproxy(lua_State *L)
{
    lua_pushcfunction(L, &proxy);
    return 1;
}

int
main(int argc, char **argv)
{
    lua_State *L;

    L = luaL_newstate();

    /* set the global function that returns the proxy */
    lua_pushcfunction(L, getproxy);
    lua_setglobal(L, "getproxy");

    /* see if it works */
    luaL_dostring(L, "p = getproxy() p('Hello, world!')");

    lua_close(L);

    return 0;
}
like image 80
Doug Currie Avatar answered May 01 '26 20:05

Doug Currie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!