Lua绑定C++类
原文: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\n", 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 \0
- lua_pushvalue( l, methodTable );
- lua_settable( l, metaTable );
- //4.0 metatable["__index"] = methodtable
- lua_pushliteral( l, "__index" );
- lua_pushvalue( l, methodTable );
- lua_rawset( l, metaTable ); // the same as lua_settable(1,metatable)
- //5.0 metatable["__gc"] = gc_animal //will be called when lua_close(l)
- lua_pushliteral( l, "__gc" );
- lua_pushcfunction( l, LuaAnimal::gc_animal );
- lua_rawset( l, metaTable );
- lua_pop(l,1); //drop metatable
- /*6.0 for object
- name -- null set object funtion to methodtable( the table on top );
- eg: Animal a = Animal("xxx")
- a:func in this methodtable
- fill methodtable, is libname is not null,
- will create a table use the libname and push the table to stack*/
- luaL_openlib( l, NULL, methods, 0 );
- lua_pop(l,1); //drop methodtable
- /*7.1 for class:
- name = className, so this set function to "method_f"
- eg: Animal a = Animal:create( "xx" );
- Animal:create() in this method_f tables
- */
- luaL_openlib( l, className, methods_f, 0 ); //push table[className] to stack
- lua_pop(l,1); //drop table[className]
- /*7.2 for class:
- add global function "className", so we Animal() is a global function now
- eg: Animal a = Animal("xx")
- function Animal() in lua will call create in C++
- */
- //lua_register(l, className, LuaAnimal::create );
- }
- int LuaAnimal::create( lua_State *l )
- {
- const char*name = lua_tostring(l,-1);
- Animal *a = new Animal(name);
- void **p = (void**)lua_newuserdata( l, sizeof(void*));
- *p = a;
- luaL_getmetatable( l, className );
- lua_setmetatable( l, -2 );
- return 1;
- }
- Animal* LuaAnimal::getAnimal( lua_State *l )
- {
- luaL_checktype( l, 1, LUA_TUSERDATA ); //indicate what type to check
- void *ud = luaL_checkudata( l, 1, className );
- if( !ud )
- luaL_typerror( l, 1, className );
- return *(Animal**)ud;
- }
- int LuaAnimal::gc_animal( lua_State *l )
- {
- Utlis::stackDump(l);
- Animal *a = (Animal*)(*(void**)lua_touserdata(l,-1));
- delete a;
- return 0;
- }
- int LuaAnimal::getAge( lua_State *l )
- {
- Animal *a = getAnimal(l);
- lua_pushinteger(l, a->getAge());
- return 1;
- }
- int LuaAnimal::setAge( lua_State *l )
- {
- Animal *a = getAnimal(l);
- int age = luaL_checkint(l,2);
- a->setAge( age );
- return 0;
- }
- int LuaAnimal::sound( lua_State *l )
- {
- Animal *a = getAnimal(l);
- a->sound();
- return 0;
- }
工具类Utils,使用查看lua堆栈情况
Utils.h
- #pragma once
- #ifndef __UTLIS_H__
- #define __UTLIS_H__
- class Utlis
- {
- public:
- Utlis(void);
- ~Utlis(void);
- static void stackDump( lua_State *l );
- };
- #endif
Utils.cpp
- #include "stdafx.h"
- #include "Utlis.h"
- Utlis::Utlis(void)
- {
- }
- Utlis::~Utlis(void)
- {
- }
- void Utlis::stackDump( lua_State *l )
- {
- int i;
- int top = lua_gettop( l );
- printf("------start-----%d\n", top);
- for( i = 1; i <= top; i++ )
- {
- int t = lua_type( l, i );
- printf("type: %s value:", lua_typename(l,t));
- switch (t)
- {
- case LUA_TSTRING:
- printf("%s", lua_tostring(l,i));
- break;
- case LUA_TBOOLEAN:
- printf( lua_toboolean(l,i)? "true" : "false" );
- break;
- case LUA_TNUMBER:
- printf("%g", lua_tonumber(l,i));
- break;
- default:
- printf("%s", lua_typename(l,t));
- break;
- }
- printf("\n");
- }
- printf("------end----\n" );
- }
lua测试代码
main.lua
- print( "test lua access C++ class" )
- local function main()
- --使用luaL_openlib( l, className, methods_f, 0 )注册,
- --Animal是个table, 调用create方法
- --local s = Animal.create("xx") --lua_gettop()=1 1:xx
- local s = Animal:create("xx") --lua_gettop()=2 1:table, 2:xx, 相比.create多了一个table,指Animal本身
- s:setAge(100)
- s:sound()
- --使用lua_register(l, className, LuaAnimal::create )注册
- --Animal是个函数,直接调用方法
- --local a = Animal("ww")
- --a:setAge(20)
- --a:sound()
- end
- main()
最后是C++测试代码
main.cpp
- // TestLua.cpp : 定义控制台应用程序的入口点。
- //
- #include "stdafx.h"
- #include "Utlis.h"
- #include "LuaAnimal.h"
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- lua_State *l = lua_open();
- luaL_openlibs(l);
- LuaAnimal::Register(l);
- Utlis::stackDump(l);
- if( luaL_dofile( l, "main.lua" )){ // load and call
- Utlis::stackDump(l);
- }
- Utlis::stackDump(l);
- system("pause");
- lua_close(l);
- return 0;
- }
Lua绑定C++类的更多相关文章
- quick-cocos2d-x 创建自定义lua绑定c++类
内容主要参考 “在quick-cocos2d-x中添加自定义的类给lua使用” ( http://www.codeo4.cn/archives/746) 1. quick-coco2d-x 使用 to ...
- Cocos2d-x v3.3 lua绑定c++类方法总结
网上有很多cocos2d-x lua绑定c++类的接口教程,这篇文章也是总结他们的经验. 其中重点参考了 http://cn.cocos2d-x.org/tutorial/show?id=1295, ...
- cocos2dx lua 绑定之二:手动绑定自定义类中的函数
cococs2dx 3.13.1 + vs2013 + win10 1.首先按照<cocos2dx lua 绑定之一:自动绑定自定义类>绑定Student类 2.在Student类中增加一 ...
- cocos2dx 2.x版本:简化提炼tolua++绑定自定义类到lua中使用
cocos2dx的3.x版本已经提供了更好地绑定方式,网上有很多相关的教程,这里给一个链接:http://www.cocoachina.com/bbs/read.php?tid=196416. 由于目 ...
- win7系统cocos2dx 3.4 绑定自定义类到Lua
Cocos2d-x 3.0开始使用bindings-generator来生成c++类的lua绑定.bindings-generator基于tolua++,通过配置tools/tolua中的ini文件以 ...
- cocos2dx lua 绑定之一:自动绑定自定义类中的函数
cococs2dx 3.13.1 + vs2013 + win10 1.首先定义C++类Student 在cocos2d-x\cocos文件夹下新建一个user_define的文件夹放置两个文件. 注 ...
- cocos2d-x lua绑定解析
花了几天时间看了下cocos2d-x lua绑定那块,总算是基本搞明白了,下面分三部分解析lua绑定: 一.lua绑定主要用到的底层函数 lua绑定其本质就是有一个公用的lua_Stack来进行C和L ...
- cocos2dx的lua绑定
一.cocos2dx对tolua++绑定的修正 A.c对lua回调函数的引用 在使用cocos2dx编写游戏时,我们经常会设置一些回调函数(时钟.菜单选择等).如果采用脚本方式编写游戏的话,这些回调函 ...
- 使用cocos2d脚本生成lua绑定
这几天要老大要求把DragonBones移到cocos2dx 3.0 里边,并且绑定lua使用接口.因为刚学lua,使用的引擎也刚从2.2改为3.0,各种不熟悉,折腾了好几天才弄完,有空了总结一下 这 ...
随机推荐
- new Handler()和new Handler(Looper.getMainLooper())的区别
一个帖子的整理: Handler一定要在主线程实例化吗?new Handler()和new Handler(Looper.getMainLooper())的区别如果你不带参数的实例化:Handler ...
- 提交svn报错说 有 unversioned 的文件
这个说明 有未add的图片等东西,需要先add进去再提交
- 关于zMPLS的设计解析
zMPLS是一个关于mpls标准实现的开源软件,它起源于2002年6月份,项目终止于2006年,目前它已经可以支持ipv6,ipv4,ldp,cr-ldp,rsvp,rsvp-te等MPLS协议簇.该 ...
- KEIL 伪指令
//为了大家查找方便,命令按字母排序:0.ALTNAME 功能: 这一伪指令用来自定义名字,以替换源程序中原来的保留字,替换的保留字均可等效地用于子程序中. 格式: ALTNAME 保留字 自定义名 ...
- 瑞柏匡丞谈中国移动app的国际进阶路
当今3.0互联时代,已然形成了一个移动化,互动化,全球化的完整体系.瑞柏匡丞也在常年与国内外客户的交流沟通中有了自己的些许见解. 国内的移动产业的发展已然非常迅速,但也正是因为各类企业的不断崛起,能够 ...
- Temporary failure in name resolution
公司搬家,在一台测试机上执行git clone,出现错误 ssh: Could not resolve hostname **: Temporary failure in name resolutio ...
- 编程:C#调用Python模块
当下,C#与Python都是比较热门的计算机编程语言,他们各有优缺点,如果能让他们互相配合工作,那是多么美好的事情,今天我来讲解一下如何利用C#来调用Python. 如果让C#支持调用Python模块 ...
- 全球扫货指南:面向中国消费者的全球奢侈品旅游导购服务 |PingWest中文网
全球扫货指南:面向中国消费者的全球奢侈品旅游导购服务 |PingWest中文网 用"全球扫货指南
- c语言通过时间种子产生随机数并选出最大值以及下标
1 #include <stdio.h> #include <stdlib.h> #include <time.h> //2016 10 10 void main( ...
- GitHub上可能用到的开源
AGi18n :https://github.com/angelolloqui/AGi18n 可以简单地本地化你的iOS app,从代码和XIB文件中提取文本转化成可本地化的字符串,且不会改变XIB文 ...