原文: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. ARM的两种启动方式 (NAND FLASH. NOR FLASH)

    为什么会有两种启动方式? 这就是有两种FLASH 的不同特点决定的. NAND FLASH 容量大,存储的单位比特数据的成本要低很多,但是要按照特定的时序对NAND  FLASH  进行读写,因此CP ...

  2. Lintcode--004(最小子串覆盖)

    给定一个字符串source和一个目标字符串target,在字符串source中找到包括所有目标字符串字母的子串. 注意事项 如果在source中没有这样的子串,返回"",如果有多个 ...

  3. Android 改变标题栏的背景色

    1:styles.xml <!-- Activity theme --> <style name="CustomTheme" parent="andro ...

  4. Bash 使用技巧大补贴

    https://linuxtoy.org/archives/the-best-tips-and-tricks-for-bash.html

  5. 瞬态抑制二极管TVS的基本知识

    二极管是大家熟悉的元件,但瞬态抑制二极管就可能不太熟悉了.本文将介绍这种特殊二极管的用途. 工作原理等基本知识.各种电子设备中的各种半导体器件,一般都在直流低电压范围各作;如果在电源中串入一个瞬间上百 ...

  6. 深入理解7816(3)-----关于T=0

    卡片和终端之间的数据传输是通过命令响应的方式进行的,卡片只能被动地接收命令,并且给出响应.所有的命令都是以命令头开始,而该命令被完整地执行后(无论结果对错),必须以包含状态字(SW1 SW2)的响应结 ...

  7. 【转】win7+ubuntu双系统安装方法--不错

    原文网址:http://blog.csdn.net/lvanneo/article/details/16885121 前段时间又安装一下win7+ubuntu双系统,过段时间就会忘记,这次自己写下来, ...

  8. Android 读取手机SD卡根目录下某个txt文件的文件内容

    1.先看activity_main.xml文件: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/and ...

  9. hdu 5423 Rikka with Tree(dfs)

    Problem Description As we know, Rikka is poor at math. Yuta is worrying about this situation, so he ...

  10. eclipse 添加resources 目录

    java项目需要一些配置,配置放置目录如:/src/main/resources; 如果没有这个文件夹,需要右键项目>new>source folder > Folder name ...