Lua C Extension: how to set metatable on new library

Kurieita Source

After multiple attempts and hours of googling I finally came to realize SOF is probably my best place to solve this.

I am currently using the Lua C API to create an extension, a shared library that you can use by requiring it via require. I am trying to do something very similar to this (sorry about the formatting):

local data = {
    something = "some"

local rpc = {}

function rpc.method()

 function rpc.method2()

   local metatable = {}
   metatable.__index = function(self, key) 
       return data[key] 
   setmetatable(rpc, metatable)

My current C code look something like this:

static int lua_index(lua_State* lua) { //idk
    std::cout << "Was indexed";
    const char* a = luaL_checkstring(lua, 2);
    std::cout << a << std::endl;
    return 0;

static int lua_initialize(lua_State* lua) {
    std::cout << "ran";
    return 0;

static const struct luaL_Reg lib[] = {
    { "initialize", lua_initialize },
    {"__index", lua_index},
    { NULL, NULL }

extern "C" int DISCORD_RPC_EXPORT luaopen_DiscordRPC(lua_State* lua) {
    luaL_newlib(lua, lib);
    lua_setmetatable(lua, 1);

    return 1;

And using this as an example:

local rpc = require "DiscordRPC"



Now obviously rpc['a'] would return nil (yes lua_index does in fact run) because lua_index isn't doing anything but why can't I call initialize? It clearly there. It says: lua: main.lua:5: attempt to call a nil value (field 'initialize') So it is nil. If I would to remove lua_setmetatable(lua, 1); I would be able to call that function but I can not index it DiscordRPC as I want to. Also I would like to point out that when I remove it the __index metamethod get called two times, obviously it would.

My question: how can I achieve this? I am trying to set a metatable on a table and return the entire metatable. Any help is very much appreciated as I am complete lost. Thank you.



answered 1 week ago Safoku #1

The problem is that setmetatable removed it from the stack. To fix this simply duplicate the value:

luaL_newlib(lua, lib);
lua_pushvalue(lua, -1);
lua_setmetatable(lua, -2);

comments powered by Disqus