#include <stdio.h>
#include "lua.h"
static int
cindex(lua_State *L)
{
lua_getglobal(L, "a");
lua_pushvalue(L, 2);
lua_gettable(L, -2);
if (!lua_isnil(L, -1))
return 1;
lua_getglobal(L, "b");
lua_pushvalue(L, 2);
lua_gettable(L, -2);
if (!lua_isnil(L, -1))
return 1;
return 0;
}
int
main(int argc, char **argv)
{
lua_State *L;
L = (lua_State *) luaL_newstate();
luaL_openlibs(L);
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");
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");
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");
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;
}
return a[k] or b[k]
。 - Judge Maygarden