【问题标题】:Lua how put userdata to C closure from metatable __index?Lua如何将用户数据从元表__index放入C闭包?
【发布时间】:2020-07-16 17:29:59
【问题描述】:

我有创建用户数据和小元表的功能

static int index_lua(lua_State *L){
    uint32_t * x;
    x = lua_touserdata(L, 1);
    printf("Buff __index ADDR: %08X\r\n", x);
    return 0;
}

static int gc_lua(lua_State *L){
    printf("Buff GC!\r\n");
    return 0;
}

static int create_buff(lua_State *L){
    uint32_t * x;

    x = (uint32_t *) lua_newuserdata(L, 512);
    printf("BUff ADDR: %08X\r\n", x);
    *x = 0;

    lua_newtable(L);
    lua_pushcfunction(L, index_lua);
    lua_setfield(L, -2, "__index");
    lua_pushcfunction(L, gc_lua);
    lua_setfield(L, -2, "__gc");
    lua_setmetatable(L, -2);

    return 1;
}

我想在 __index (index_lua) 中创建新的 C 函数并将用户数据放入他的闭包(upvalue),但我无法理解它是如何做到的。我可以放一个指向用户数据的指针。但我认为这是个坏主意,因为如果 Lua 不知道在某些功能中使用了哪些用户数据,Lua 可以在进行垃圾收集时删除用户数据。

【问题讨论】:

    标签: c lua closures metatable


    【解决方案1】:

    需要从堆栈中移除函数__index的第二个参数,并且在关闭堆栈的一个元素之后它将是一个用户数据。

    static int index_lua(lua_State *L){
        uint32_t * x;
        x = lua_touserdata(L, 1);
        printf("Buff __index ADDR: %08X\r\n", x);
        lua_pop(L,1); // Remove second param __index
        lua_pushcclosure (L, test, 1); // put on stack 1 element of stack
        return 1;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-21
      • 2017-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-28
      • 2012-11-28
      • 1970-01-01
      • 2018-05-05
      相关资源
      最近更新 更多