Lua C API and metatable functions
snippet in lua

Lua C API and metatable functions

user9952

#include <stdio.h>
#include "lua.h"

/* __index metamethod for the 'c' table (stack: 1 = table 'c', 2 = desired index) */
static int
cindex(lua_State *L)
{
    /* try the global 'a' table */
    lua_getglobal(L, "a");
    lua_pushvalue(L, 2);
    lua_gettable(L, -2);
    if (!lua_isnil(L, -1))
        return 1;

    /* try the global 'b' table */
    lua_getglobal(L, "b");
    lua_pushvalue(L, 2);
    lua_gettable(L, -2);
    if (!lua_isnil(L, -1))
        return 1;

    /* return nil */
    return 0;
}

int
main(int argc, char **argv)
{
    lua_State *L;

    L = (lua_State *) luaL_newstate();
    luaL_openlibs(L);

    /* create the global 'a' table */
    lua_createtable(L, 0, 2);
    lua_pushstring(L, "1");
    lua_setfield(L, -2, "one");
    lua_pushstring(L, "2");
    lua_setfield(L, -2, "two");
    lua_setglobal(L, "a");

    /* create the global 'b' table */
    lua_createtable(L, 0, 2);
    lua_pushstring(L, "3");
    lua_setfield(L, -2, "three");
    lua_pushstring(L, "4");
    lua_setfield(L, -2, "four");
    lua_setglobal(L, "b");

    /* create the global 'c' table and use a C function as the __index metamethod */
    lua_createtable(L, 0, 0);
    lua_createtable(L, 0, 1);
    lua_pushcfunction(L, cindex);
    lua_setfield(L, -2, "__index");
    lua_setmetatable(L, -2);
    lua_setglobal(L, "c");

    /* run the test script */
    luaL_loadstring(L, "print(c.one)\nprint(c.four)");
    if (0 != lua_pcall(L, 0, 0, 0)) {
        puts(lua_tostring(L, -1));
        return 1;
    }

    return 0;
}