原文:http://blog.csdn.net/chenee543216/article/details/12074771
以下是代码:
Animal.h文件
- #pragma once
- #ifndef __ANIMAL_H__
- #define __ANIMAL_H__
- class Animal
- {
- public:
- Animal( const char *name );
- void setAge( int age );
- int getAge();
- void sound();
- ~Animal(void);
- private:
- const char *name;
- int age;
- };
- #endif
Animal.cpp文件
- #include "stdafx.h"
- #include "Animal.h"
- Animal::Animal( const char* name ):age(0)
- {
- this->name = name;
- }
- Animal::~Animal(void)
- {
- printf( "Animal destructor." );
- }
- void Animal::setAge( int age )
- {
- this->age = age;
- }
- int Animal::getAge()
- {
- return this->age;
- }
- void Animal::sound()
- {
- printf("--Animal-- name: %s, age:%d ", this->name, this->age );
- }
LuaAimal.h
- #pragma once
- #ifndef __LUA_ANIMAL__
- #define __LUA_ANIMAL__
- class Animal;
- class LuaAnimal
- {
- public:
- ~LuaAnimal(void);
- static void Register( lua_State *l );
- private:
- static const char *className;
- static const luaL_reg methods[];
- static const luaL_reg methods_f[];
- static int create( lua_State *l );
- static int gc_animal( lua_State *l );
- static Animal *getAnimal( lua_State *l );
- static int sound( lua_State *l );
- static int setAge(lua_State *l);
- static int getAge(lua_State *l);
- };
- #endif
LuaAnimal.cpp
- #include "stdafx.h"
- #include "LuaAnimal.h"
- #include "Animal.h"
- #include "Utlis.h"
- const char *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[] = {
- { "create", LuaAnimal::create },
- { NULL, NULL}
- };
- LuaAnimal::~LuaAnimal(void)
- {
- }
- void LuaAnimal::Register( lua_State *l )
- {
- //1. new method table for l to save functions
- lua_newtable(l);
- int methodTable = lua_gettop(l);
- //2.new metatable for L to save "__metatable", "__index", "__gc", etc
- luaL_newmetatable(l, className );
- int metaTable = lua_gettop(l);
- //3.0 metatable["__metatable"] = methodtable;
- lua_pushliteral( l, "__metatable" ); //remove