lua - 推送可执行函数指针?

标签 lua

通常只有当数据不是任何 Lua 标准类型(数字、字符串、 bool 等)时,才会推送“用户数据”。

但是你如何将一个实际的函数指针推送到 Lua(不是作为 userdata;因为 userdata 在 Lua 中不能作为函数执行),假设函数看起来像这样:

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

返回值的行为应该与 native Lua 函数的返回值类似:

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

这可能与 C API 相关吗?如果是,如何(示例将不胜感激)?

编辑:为了清楚起见,该值应该由通过 C API 公开给 Lua 的函数返回。

最佳答案

使用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;
}

关于lua - 推送可执行函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4210644/

相关文章:

string - 在 Lua 中匹配即将到来的日期

C++模板方法创建对象

lua - "loadall.so"是什么?

lua - Torch,为什么我的人工神经网络总是预测为零?

lua - kong环境下出现错误 "plugin is in use but not enabled"

c++ - 扩展 Lua : check number of parameters passed to a function

mysql - os.date 函数没有返回期望的结果

Ruby 沙盒与集成脚本语言

syntax - lua (Syntax) : Calling a function that returns more than 1 value, 并使用这些值作为参数,但没有额外的变量赋值行?

c - 如何在c中获取lua参数?