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,各种不熟悉,折腾了好几天才弄完,有空了总结一下 这 ...
随机推荐
- [T]各种字符串Hash函数比较
常用的字符串Hash函数还有ELFHash,APHash等等,都是十分简单有效的方法.这些函数使用位运算使得每一个字符都对最后的函数值产生影响.另外还有以MD5和SHA1为代表的杂凑函数,这些函数几乎 ...
- SolrCloud初识
文章摘自:http://www.bubuko.com/infodetail-923588.html 一.概述 Lucene是一个Java语言编写的利用倒排原理实现的文本检索类库: Solr是以Luce ...
- Android-4
显式Intent 隐式Intent Intent过滤器相关选项 通过浏览器链接启动本地Activity
- caffe 中的一些参数介绍
转自:http://blog.csdn.net/cyh_24/article/details/51537709 solver.prototxt net: "models/bvlc_alexn ...
- Lintcode--008(编辑距离)
http://www.lintcode.com/en/problem/edit-distance/ 2016-08-29 给出两个单词word1和word2,计算出将word1 转换为word2的最少 ...
- TEncoding & TNetEncoding(使用现成的TBase64Encoding,TEncoding和TMBCSEncoding)
TEncoding and TNetEncoding are abstract classes and you will never instantiate one of them, because ...
- 实现ECMAScript的引擎
list of ECMAScript engines From Wikipedia, the free encyclopedia An ECMAScript engine is a progr ...
- logstash nginx 报ArgumentError: comparison of String with 5 failed
80.82.78.38 [23/Sep/2016:05:36:18 +0800] "GET http://www.baidu.com/cache/global/img/gs.gif HTTP ...
- poj 1328 Radar Installation(贪心)
Description Assume the coasting is an infinite straight line. Land is in one side of coasting, sea i ...
- 【转载自i春秋】图片马合成方法
1.将图片和一句话木马放在同一个文件夹 2.创建快捷方式,将起始位置修改为图片和txt文本的路径. 3.进行合成,命令如下 copy .png /b + .txt /a .png 4.成功!自行测试. ...