Saving C structure in Lua registry

As I integrate Lua into my C program, I used a pointer staticto the C structure to store the object that I need to reuse in the methods that I bind to the Lua state.

However, this will not work when I split Lua lib from the main program, so it seems to me that I need to use the registry to store my structure.

How do I put my C structure pointer in the Lua registry?

This is what I am doing now:

static augeas *aug = NULL;


static int lua_aug_get(lua_State *L) {
    // Use aug to do something here
    /* return the number of results */
    return 1;
}

struct lua_State *luaopen_augeas(augeas *a) {
    lua_State *L = luaL_newstate();
    aug = a; // this clearly does not work
    luaL_openlibs(L);
    // The methods below will need to access the augeas * struct
    // so I need to push it to the registry (I guess)
    static const luaL_Reg augfuncs[] = {
        { "get", lua_aug_get },
        { "label", lua_aug_label },
        { "set", lua_aug_set },
        { NULL, NULL }
    };

    luaL_newlib(L, augfuncs);
    lua_setglobal(L, "aug");

    return L;
}

Edit: from the answer I received in the IRC, it seems that I should use metatable , so I'm studying this now.

+4
source share
2 answers

- , :

static int lua_aug_get(lua_State *L) {
  augeas *aug = lua_touserdata(L, lua_upvalueindex(1));
  // Do stuff with aug
  return 1;
}

static const luaL_Reg augfuncs[] = {
    { "get", lua_aug_get },
    { "label", lua_aug_label },
    { "set", lua_aug_set },
    { NULL, NULL }
};
lua_createtable(L, 0, 0);
for (size_t i = 0; augfuncs[i].name; i++) {
    lua_pushlightuserdata(L, a);
    lua_pushcclosure(L, augfuncs[i].func, 1);
    lua_setfield(L, -2, augfuncs[i].name);
}

. script -, debug, . , .

+3

Lua :

static const char *Key = "augeas_registry_key"; // The registry key

static augeas *checkaug(lua_State *L) {
  lua_pushlightuserdata(L, (void *)&Key);        // set the registry key
  lua_gettable(L, LUA_REGISTRYINDEX);            // retrieve value
  augeas *aug = (augeas *)lua_touserdata(L, -1); // cast value
  return aug;
}

static int lua_aug_get(lua_State *L) {
  augeas *aug = checkaug(L);
  // Do stuff with aug
  return 1;
}

struct lua_State *luaopen_augeas(augeas *a) {
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    lua_pushlightuserdata(L, (void *)&Key); // set registry key
    lua_pushlightuserdata(L, (void *)a);    // push pointer
    lua_settable(L, LUA_REGISTRYINDEX);     // push to in registry

    static const luaL_Reg augfuncs[] = {
        { "get", lua_aug_get },
        { "label", lua_aug_label },
        { "set", lua_aug_set },
        { NULL, NULL }
    };

    luaL_newlib(L, augfuncs);
    lua_setglobal(L, "aug");

    return L;
}

, , , , , , .

+1

Source: https://habr.com/ru/post/1608770/


All Articles