Lua C API和元表函数

4

我是一个C应用程序中使用Lua,有两个表。我想创建一个第三个表,虽然它是空的,但可以从我的前两个表中索引值。我在Lua中编写了以下简单示例 -

a = { one="1", two="2" }
b = { three="3", four="4" }

meta = { __index = function(t,k)
  if a[k] == nil then return b[k]
  else return a[k] end
end }

c = {}
setmetatable(c, meta)

print(c.one) -- prints "1"
print(c.four) -- prints "4"

我的问题是,从C API中最有效的方法是什么?我已经通过创建一个新表,在该表上推送上面的Lua代码块,然后调用setmetatable()来完成这个操作,但这似乎不太理想。有更好的方法吗?


3
顺便提一句,你的__index函数可以简化为return a[k] or b[k] - Judge Maygarden
6
@Judge Maygarden: 如果 a[k] 可能为假,则不成立。 - daurnimator
2个回答

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

2

你能修改b的元表吗?如果可以的话,这种方式更加高效:

a = { one="1", two="2" }
b = { three="3", four="4" }

setmetatable(a, { __index = b })

-- setmetatable(x, m) returns x, so you can do this:
c = setmetatable({}, { __index = a }) -- meta is here, too

print(c.one) -- prints "1"
print(c.four) -- prints "4"

__index指向一个表时,它比指向一个函数更有效;我在某个地方读到过,这相当于C中的3个间接引用。所以在最坏的情况下(c.one),总共有6个间接引用。


1
正如此处所展示的,b优于a;而不是问题中所呈现的相反情况。只是小小的挑剔。 - Joseph Mariadassou
@JosephMariadassou 感谢您的评论,我已经调整了依赖项的顺序,使得首先查看 a 而不是最后一个。 - kikito

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接