原文: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. /dev/socket/vold exploit 本地提权漏洞

    EXPLOIT "0 asec create ../../../../../../../../xxxxx/xx/xx/xx 1 ext4 98235792350852308254872354 ...

  2. hadoop SQL使用

    转载自:http://slaytanic.blog.51cto.com/2057708/782175 Hive 是facebook开源的一个基于hadoop框架的查询工具,也就是说,需要用hive的话 ...

  3. NSNumber与NSInteger的区别 -bei

    基本类型,如同C 语言中的 int 类型一样,拿来就可以直接用. 而类在使用时,必须先创建一个对象,再为对象分配空间,接着做初始化和赋值. 类的初始化,需用类自身的方法 (类方法). 代码中所创建的对 ...

  4. GridView 中Item项居中显示

    直接在GridView中设置 android:gravity="center"这个属性是不起作用的.要在你adapter中的布局文件中设 置android:layout_gravi ...

  5. 树莓派入门教程——使用Qt开发界面程序

    前言        Qt是一个1991年由奇趣科技开发的跨平台C++图形用户界面应用程序开发框架.它既可以开发GUI程序,也可用于开发非GUI程序,比如控制台工具和服务器.Qt是面向对象的框架,使用特 ...

  6. Thread的run()与start()的区别

    Java的线程是通过java.lang.Thread类来实现的.VM启动时会有一个由主方法所定义的线程.可以通过创建Thread的实例来创建新的线程.每个线程都是通过某个特定Thread对象所对应的方 ...

  7. mysql sql优化<1>

    <pre name="code" class="html">explain SELECT t.* FROM ( SELECT t1.sn AS cl ...

  8. bzoj1149

    题目:http://www.lydsy.com/JudgeOnline/problem.php?id=1149 水题..... 直接BFS. #include<cstdio> #inclu ...

  9. WEB 移动网站 手机点击 打电话 发短信

    原文地址: http://www.blesswe.com/portal.php?mod=view&aid=428 我们在手机浏览网页是希望用户看到手机号码点击就可以直接打电话或发短信,下面我们 ...

  10. c++之命名空间namespace

    1命名空间解决全局变量的冲突 main.h文件 #pragma once // data命名空间的名称 namespace data { ;//外部全局变量冲突 } main.cpp #include ...