我想知道如何从http://lua-users.org/wiki/MetamethodsTutorial
编写类似Lua Snippet的内容local func_example = setmetatable({}, {__index = function (t, k)
return "key doesn't exist"
end})
local fallback_tbl = setmetatable({
foo = "bar",
[123] = 456,
}, {__index=func_example})
local fallback_example = setmetatable({}, {__index=fallback_tbl})
print(func_example[1]) --> key doesn't exist
print(fallback_example.foo) --> bar
print(fallback_example[123]) --> 456
print(fallback_example[456]) --> key doesn't exist
在lua C api中。即我希望lua首先检查一个密钥是否在成员metatable中,否则调用__index实现。我想出了类似的东西:
static const struct luaL_reg
lobj_fallback[] = {
{"__index", lobject_index},
{"__newindex", lobject_newindex},
{"__tostring", lobject_tostring},
{NULL, NULL},
};
static const struct luaL_reg
lobj_members[] = {
{"delete", lobject_delete},
{NULL, NULL}
};
{
// ....
luaL_newmetatable(L, "MyMetaTable");
luaL_register(L, NULL, lobj_members);
luaL_newmetatable(L, "MyMetaTableFallback");
luaL_register(L, NULL, lobj_fallback);
lua_setmetatable(L, -2);
// ...
}
然而,这不能按预期工作,处理后备__index工作但不是成员metatable(&#34;尝试调用方法&#39;删除&#39;(零值)&#34;)。< / p>
答案 0 :(得分:4)
如果您打算在访问“MyMetaTable”时回退到索引功能,那么您已经交换了表和metatable的名称。因此,成员表(lobj_members)被称为“MyMetaTableFallback”,metatable(lobj_fallback)被称为“MyMetaTable”。