lua 操作 C++的类 ;manipulate c++ class with lua(二)

2014-11-23 23:11:54 · 作者: · 浏览: 10
luaL_typerror(L,1,className.c_str());
}
return *(Animal**)ud;
}
static int sound(lua_State *L){
Animal *a = getAnimal(L);
a->sound();
return 1;
}
static int setAge(lua_State *L){
Animal *a = getAnimal(L);
double age = luaL_checknumber(L, 2);
a->setAge(int(age));
return 0;
}
static int getAge(lua_State *L){
Animal *a = getAnimal(L);
int age = a->getAge();
lua_pushinteger(L, age);
return 1;
}
public:
static void Register(lua_State* L) {
//1: new methods talbe for L to save functions
lua_newtable(L);
int methodtable = lua_gettop(L);
//2: new metatable for L to save "__index" "__newindex" "__gc" "__metatable" ...
luaL_newmetatable(L, className.c_str());
int metatable = lua_gettop(L);
//3: metatable["__metatable"] = methodtable
lua_pushliteral(L, "__metatable");
lua_pushvalue(L, methodtable);
lua_settable(L, metatable); // hide metatable from Lua getmetatable()
//4: metatable["__index"] = methodtable
lua_pushliteral(L, "__index");
lua_pushvalue(L, methodtable);
lua_settable(L, metatable);
//5: metatable["__gc"] = gc_animal
lua_pushliteral(L, "__gc");
lua_pushcfunction(L, gc_animal);
lua_settable(L, metatable);
lua_pop(L, 1); // drop metatable
//6: for objct:
// name == 0 set object function to "methods"
//eg:Animal a = Animal("xx");
//a:func() in this "methods" table;
luaL_openlib(L, 0, methods, 0); // fill methodtable
lua_pop(L, 1); // drop methodtable
//7.1: for Class:
//name = "classname" , so this set Class function to "methods_f"
//eg:Animal a = Animal:creat("xx");
//Animal:creat() in this "methods_f" tables;
// luaL_openlib(L, className.c_str(), methods_f, 0);
//7.2: for Class:
//add global function "Classname", so we Animal() is a global function now
//Animal a = Animal("xx");
//function Animal()in lua will call "creat" in C++
lua_register(L, className.c_str(), creat);
}
};
const string LuaAnimal::className = "Animal";
const luaL_reg LuaAnimal::methods[] = {
{"sound", LuaAnimal::sound},
{"setAge", LuaAnimal::setAge},
{"getAge", LuaAnimal::getAge},
{"__gc", LuaAnimal::gc_animal},
{NULL, NULL}
};
const luaL_reg LuaAnimal::methods_f[] = {
{"creat", LuaAnimal::creat},
{NULL, NULL}
};
int main()
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
//
LuaAnimal::Register(L);
if (luaL_loadfile(L, "chenee.lua") || lua_pcall(L, 0, 0, 0)){
cout << "cannot run config. file:" << lua_tostring(L,-1) << endl;
}
lua_close(L);
return 0;
}