原文:http://blog.csdn.net/chenee543216/article/details/12074771

以下是代码:

Animal.h文件

  1. #pragma once
  2. #ifndef __ANIMAL_H__
  3. #define __ANIMAL_H__
  4. class Animal
  5. {
  6. public:
  7. Animal( const char *name );
  8. void setAge( int age );
  9. int getAge();
  10. void sound();
  11. ~Animal(void);
  12. private:
  13. const char *name;
  14. int age;
  15. };
  16. #endif

Animal.cpp文件

  1. #include "stdafx.h"
  2. #include "Animal.h"
  3. Animal::Animal( const char* name ):age(0)
  4. {
  5. this->name = name;
  6. }
  7. Animal::~Animal(void)
  8. {
  9. printf( "Animal destructor." );
  10. }
  11. void Animal::setAge( int age )
  12. {
  13. this->age = age;
  14. }
  15. int Animal::getAge()
  16. {
  17. return this->age;
  18. }
  19. void Animal::sound()
  20. {
  21. printf("--Animal-- name: %s, age:%d\n", this->name, this->age );
  22. }

LuaAimal.h

  1. #pragma once
  2. #ifndef __LUA_ANIMAL__
  3. #define __LUA_ANIMAL__
  4. class Animal;
  5. class LuaAnimal
  6. {
  7. public:
  8. ~LuaAnimal(void);
  9. static void Register( lua_State *l );
  10. private:
  11. static const char *className;
  12. static const luaL_reg methods[];
  13. static const luaL_reg methods_f[];
  14. static int create( lua_State *l );
  15. static int gc_animal( lua_State *l );
  16. static Animal *getAnimal( lua_State *l );
  17. static int sound( lua_State *l );
  18. static int setAge(lua_State *l);
  19. static int getAge(lua_State *l);
  20. };
  21. #endif

LuaAnimal.cpp

  1. #include "stdafx.h"
  2. #include "LuaAnimal.h"
  3. #include "Animal.h"
  4. #include "Utlis.h"
  5. const char *LuaAnimal::className = "Animal";
  6. const luaL_reg LuaAnimal::methods[] = {
  7. {"sound", LuaAnimal::sound },
  8. {"setAge", LuaAnimal::setAge},
  9. {"getAge", LuaAnimal::getAge},
  10. {"__gc", LuaAnimal::gc_animal},
  11. {NULL,NULL}
  12. };
  13. const luaL_reg LuaAnimal::methods_f[] = {
  14. { "create", LuaAnimal::create },
  15. { NULL, NULL}
  16. };
  17. LuaAnimal::~LuaAnimal(void)
  18. {
  19. }
  20. void LuaAnimal::Register( lua_State *l )
  21. {
  22. //1. new method table for l to save functions
  23. lua_newtable(l);
  24. int methodTable = lua_gettop(l);
  25. //2.new metatable for L to save "__metatable", "__index",  "__gc", etc
  26. luaL_newmetatable(l, className );
  27. int metaTable = lua_gettop(l);
  28. //3.0 metatable["__metatable"] = methodtable;
  29. lua_pushliteral( l, "__metatable" );  //remove \0
  30. lua_pushvalue( l, methodTable );
  31. lua_settable( l, metaTable );
  32. //4.0 metatable["__index"] = methodtable
  33. lua_pushliteral( l, "__index" );
  34. lua_pushvalue( l, methodTable );
  35. lua_rawset( l, metaTable );  // the same as lua_settable(1,metatable)
  36. //5.0 metatable["__gc"] = gc_animal  //will be called when lua_close(l)
  37. lua_pushliteral( l, "__gc" );
  38. lua_pushcfunction( l, LuaAnimal::gc_animal );
  39. lua_rawset( l, metaTable );
  40. lua_pop(l,1);   //drop metatable
  41. /*6.0 for object
  42. name -- null set object funtion to methodtable( the table on top );
  43. eg: Animal a = Animal("xxx")
  44. a:func in this methodtable
  45. fill methodtable, is libname is not null,
  46. will create a table use the libname and push the table to stack*/
  47. luaL_openlib( l, NULL, methods, 0 );
  48. lua_pop(l,1);       //drop methodtable
  49. /*7.1 for class:
  50. name = className, so this set function to "method_f"
  51. eg: Animal a = Animal:create( "xx" );
  52. Animal:create() in this method_f tables
  53. */
  54. luaL_openlib( l, className, methods_f, 0 );  //push table[className] to stack
  55. lua_pop(l,1); //drop table[className]
  56. /*7.2 for class:
  57. add global function "className", so we Animal() is a global function now
  58. eg: Animal a = Animal("xx")
  59. function Animal() in lua will call create in C++
  60. */
  61. //lua_register(l, className, LuaAnimal::create );
  62. }
  63. int LuaAnimal::create( lua_State *l )
  64. {
  65. const char*name = lua_tostring(l,-1);
  66. Animal *a = new Animal(name);
  67. void **p = (void**)lua_newuserdata( l, sizeof(void*));
  68. *p = a;
  69. luaL_getmetatable( l, className );
  70. lua_setmetatable( l, -2 );
  71. return 1;
  72. }
  73. Animal* LuaAnimal::getAnimal( lua_State *l )
  74. {
  75. luaL_checktype( l, 1, LUA_TUSERDATA ); //indicate what type to check
  76. void *ud = luaL_checkudata( l, 1, className );
  77. if( !ud )
  78. luaL_typerror( l, 1, className );
  79. return *(Animal**)ud;
  80. }
  81. int LuaAnimal::gc_animal( lua_State *l )
  82. {
  83. Utlis::stackDump(l);
  84. Animal *a = (Animal*)(*(void**)lua_touserdata(l,-1));
  85. delete a;
  86. return 0;
  87. }
  88. int LuaAnimal::getAge( lua_State *l )
  89. {
  90. Animal *a = getAnimal(l);
  91. lua_pushinteger(l, a->getAge());
  92. return 1;
  93. }
  94. int LuaAnimal::setAge( lua_State *l )
  95. {
  96. Animal *a = getAnimal(l);
  97. int age = luaL_checkint(l,2);
  98. a->setAge( age );
  99. return 0;
  100. }
  101. int LuaAnimal::sound( lua_State *l )
  102. {
  103. Animal *a = getAnimal(l);
  104. a->sound();
  105. return 0;
  106. }

工具类Utils,使用查看lua堆栈情况

Utils.h

  1. #pragma once
  2. #ifndef __UTLIS_H__
  3. #define __UTLIS_H__
  4. class Utlis
  5. {
  6. public:
  7. Utlis(void);
  8. ~Utlis(void);
  9. static void stackDump( lua_State *l );
  10. };
  11. #endif

Utils.cpp

  1. #include "stdafx.h"
  2. #include "Utlis.h"
  3. Utlis::Utlis(void)
  4. {
  5. }
  6. Utlis::~Utlis(void)
  7. {
  8. }
  9. void Utlis::stackDump( lua_State *l )
  10. {
  11. int i;
  12. int top = lua_gettop( l );
  13. printf("------start-----%d\n", top);
  14. for( i = 1; i <= top; i++ )
  15. {
  16. int t = lua_type( l, i );
  17. printf("type: %s value:", lua_typename(l,t));
  18. switch (t)
  19. {
  20. case LUA_TSTRING:
  21. printf("%s", lua_tostring(l,i));
  22. break;
  23. case LUA_TBOOLEAN:
  24. printf( lua_toboolean(l,i)? "true" : "false" );
  25. break;
  26. case LUA_TNUMBER:
  27. printf("%g", lua_tonumber(l,i));
  28. break;
  29. default:
  30. printf("%s", lua_typename(l,t));
  31. break;
  32. }
  33. printf("\n");
  34. }
  35. printf("------end----\n" );
  36. }

lua测试代码

main.lua

  1. print( "test lua access C++ class" )
  2. local function main()
  3. --使用luaL_openlib( l, className, methods_f, 0 )注册,
  4. --Animal是个table, 调用create方法
  5. --local s = Animal.create("xx") --lua_gettop()=1 1:xx
  6. local s = Animal:create("xx") --lua_gettop()=2 1:table, 2:xx, 相比.create多了一个table,指Animal本身
  7. s:setAge(100)
  8. s:sound()
  9. --使用lua_register(l, className, LuaAnimal::create )注册
  10. --Animal是个函数,直接调用方法
  11. --local a = Animal("ww")
  12. --a:setAge(20)
  13. --a:sound()
  14. end
  15. main()

最后是C++测试代码

main.cpp

    1. // TestLua.cpp : 定义控制台应用程序的入口点。
    2. //
    3. #include "stdafx.h"
    4. #include "Utlis.h"
    5. #include "LuaAnimal.h"
    6. using namespace std;
    7. int _tmain(int argc, _TCHAR* argv[])
    8. {
    9. lua_State *l = lua_open();
    10. luaL_openlibs(l);
    11. LuaAnimal::Register(l);
    12. Utlis::stackDump(l);
    13. if( luaL_dofile( l, "main.lua" )){  // load and call
    14. Utlis::stackDump(l);
    15. }
    16. Utlis::stackDump(l);
    17. system("pause");
    18. lua_close(l);
    19. return 0;
    20. }

Lua绑定C++类的更多相关文章

  1. quick-cocos2d-x 创建自定义lua绑定c++类

    内容主要参考 “在quick-cocos2d-x中添加自定义的类给lua使用” ( http://www.codeo4.cn/archives/746) 1. quick-coco2d-x 使用 to ...

  2. Cocos2d-x v3.3 lua绑定c++类方法总结

    网上有很多cocos2d-x lua绑定c++类的接口教程,这篇文章也是总结他们的经验. 其中重点参考了 http://cn.cocos2d-x.org/tutorial/show?id=1295, ...

  3. cocos2dx lua 绑定之二:手动绑定自定义类中的函数

    cococs2dx 3.13.1 + vs2013 + win10 1.首先按照<cocos2dx lua 绑定之一:自动绑定自定义类>绑定Student类 2.在Student类中增加一 ...

  4. cocos2dx 2.x版本:简化提炼tolua++绑定自定义类到lua中使用

    cocos2dx的3.x版本已经提供了更好地绑定方式,网上有很多相关的教程,这里给一个链接:http://www.cocoachina.com/bbs/read.php?tid=196416. 由于目 ...

  5. win7系统cocos2dx 3.4 绑定自定义类到Lua

    Cocos2d-x 3.0开始使用bindings-generator来生成c++类的lua绑定.bindings-generator基于tolua++,通过配置tools/tolua中的ini文件以 ...

  6. cocos2dx lua 绑定之一:自动绑定自定义类中的函数

    cococs2dx 3.13.1 + vs2013 + win10 1.首先定义C++类Student 在cocos2d-x\cocos文件夹下新建一个user_define的文件夹放置两个文件. 注 ...

  7. cocos2d-x lua绑定解析

    花了几天时间看了下cocos2d-x lua绑定那块,总算是基本搞明白了,下面分三部分解析lua绑定: 一.lua绑定主要用到的底层函数 lua绑定其本质就是有一个公用的lua_Stack来进行C和L ...

  8. cocos2dx的lua绑定

    一.cocos2dx对tolua++绑定的修正 A.c对lua回调函数的引用 在使用cocos2dx编写游戏时,我们经常会设置一些回调函数(时钟.菜单选择等).如果采用脚本方式编写游戏的话,这些回调函 ...

  9. 使用cocos2d脚本生成lua绑定

    这几天要老大要求把DragonBones移到cocos2dx 3.0 里边,并且绑定lua使用接口.因为刚学lua,使用的引擎也刚从2.2改为3.0,各种不熟悉,折腾了好几天才弄完,有空了总结一下 这 ...

随机推荐

  1. new Handler()和new Handler(Looper.getMainLooper())的区别

    一个帖子的整理: Handler一定要在主线程实例化吗?new Handler()和new Handler(Looper.getMainLooper())的区别如果你不带参数的实例化:Handler ...

  2. 提交svn报错说 有 unversioned 的文件

    这个说明   有未add的图片等东西,需要先add进去再提交

  3. 关于zMPLS的设计解析

    zMPLS是一个关于mpls标准实现的开源软件,它起源于2002年6月份,项目终止于2006年,目前它已经可以支持ipv6,ipv4,ldp,cr-ldp,rsvp,rsvp-te等MPLS协议簇.该 ...

  4. KEIL 伪指令

    //为了大家查找方便,命令按字母排序:0.ALTNAME 功能: 这一伪指令用来自定义名字,以替换源程序中原来的保留字,替换的保留字均可等效地用于子程序中. 格式: ALTNAME 保留字 自定义名 ...

  5. 瑞柏匡丞谈中国移动app的国际进阶路

    当今3.0互联时代,已然形成了一个移动化,互动化,全球化的完整体系.瑞柏匡丞也在常年与国内外客户的交流沟通中有了自己的些许见解. 国内的移动产业的发展已然非常迅速,但也正是因为各类企业的不断崛起,能够 ...

  6. Temporary failure in name resolution

    公司搬家,在一台测试机上执行git clone,出现错误 ssh: Could not resolve hostname **: Temporary failure in name resolutio ...

  7. 编程:C#调用Python模块

    当下,C#与Python都是比较热门的计算机编程语言,他们各有优缺点,如果能让他们互相配合工作,那是多么美好的事情,今天我来讲解一下如何利用C#来调用Python. 如果让C#支持调用Python模块 ...

  8. 全球扫货指南:面向中国消费者的全球奢侈品旅游导购服务 |PingWest中文网

    全球扫货指南:面向中国消费者的全球奢侈品旅游导购服务 |PingWest中文网 用"全球扫货指南

  9. c语言通过时间种子产生随机数并选出最大值以及下标

    1 #include <stdio.h> #include <stdlib.h> #include <time.h> //2016 10 10 void main( ...

  10. GitHub上可能用到的开源

    AGi18n :https://github.com/angelolloqui/AGi18n 可以简单地本地化你的iOS app,从代码和XIB文件中提取文本转化成可本地化的字符串,且不会改变XIB文 ...