Search code examples
cluaclosuresmetatable

Lua how put userdata to C closure from metatable __index?


I have function what create user data and little metatable

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

I want in __index (index_lua), create new C Function and put userdata to his closure(upvalue), but i cant undertand how its do it. I can put a pointer to userdata. But i think its bad idea because Lua can remove userdata when do garbage collection if his not know what user data using in some functions.


Solution

  • Need remove from stack second parametr of function __index, and after out to close one element of stack its will be a userdata.

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