推送可执行函数指针?

2 lua

通常只有当数据不是Lua的标准类型(数字,字符串,bool等)时,才会推送'userdata'.

但是你如何将实际的Function指针推送到Lua(而不是userdata;因为userdata在Lua中不能作为函数执行),假设函数如下所示:

void nothing(const char* stuff)
{
    do_magic_things_with(stuff);
}
Run Code Online (Sandbox Code Playgroud)

返回的值应该类似于此本机Lua函数的返回值:

function things()
    return function(stuff)
        do_magic_things_with(stuff)
    end
end
Run Code Online (Sandbox Code Playgroud)

这可能与C API有关吗?如果是,如何(例子将被赞赏)?

编辑:为了增加一些清晰度,该值应该由通过C API向Lua公开的函数返回.

Dou*_*rie 10

使用 lua_pushcfunction

例子包括在PiL中

这是一个遵循当前接受的答案形式的示例.

#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;
}
Run Code Online (Sandbox Code Playgroud)

  • 这是事实,但是可以创建类型为lua_CFunction的函数来从Lua堆栈中提取参数并将它们传递给目标C函数.这称为创建绑定! (4认同)