printf "static int luaM_%s_index(lua_State *L)\n{\n" pkg.name;
printf " const char *idx = luaL_checkstring(L, 2);\n\n";
printf " switch (mlua_which_token(idx, -1)) {\n";
- printf " default:\n";
List.iter (function (m, _, _) ->
printf " case LTK_%s:\n" (upper m.mname);
let push, f, l = (snd m.typ).push in
printf " %s;\n" (tplize push (sprintf "%s.%s" pkg.name m.mname));
printf " return 1;\n"
) pkg.members;
- printf " lua_rawget(L, lua_upvalueindex(2));\n";
+ printf " default:\n";
+ printf " lua_rawget(L, lua_upvalueindex(1));\n";
printf " return 1;\n";
printf " }\n}\n\n";
printf " return 1;\n"
) pkg.members;
printf " default:\n";
+ printf " lua_rawset(L, lua_upvalueindex(1));\n";
printf " return 1;\n";
printf " }\n}\n";
int luaopen_%s(lua_State *L)
{
- int mt, methods;
+ int mt, members, methods;
%s_init();
luaL_openlib(L, \"%s\", luaM_%s_methods, 0);
methods = lua_gettop(L);
+ lua_newtable(L); /* for new members */
+ members = lua_gettop(L);
+
/* create metatable for %s, add it to the registry */
luaL_newmetatable(L, \"%s\");
mt = lua_gettop(L);
lua_pushliteral(L, \"__index\");
- lua_pushvalue(L, mt); /* upvalue 1 */
- lua_pushvalue(L, methods); /* upvalue 2 */
- lua_pushcclosure(L, &luaM_%s_index, 2);
+ lua_pushvalue(L, members); /* upvalue 1 */
+ lua_pushcclosure(L, &luaM_%s_index, 1);
lua_rawset(L, mt); /* set mt.__index */
lua_pushliteral(L, \"__newindex\");
- lua_newtable(L); /* for new members */
+ lua_pushvalue(L, members); /* upvalue 1 */
lua_pushcclosure(L, &luaM_%s_newindex, 1);
lua_rawset(L, mt); /* set mt.__newindex */
lua_setmetatable(L, methods);
- lua_pop(L, 2); /* drop mt + methods */
+ lua_pop(L, 3);
return 1;
}