cocos2dx与lua

本文介绍了如何在Cocos2dx中使用Lua脚本,包括通过tolua++注册自定义类型和接口,以及如何在C++对象中调用Lua全局函数进行AI逻辑处理。示例中展示了如何在cwGameObject类中调用Lua的do_obj_update函数进行对象更新。
摘要由CSDN通过智能技术生成
闲来无事,搞了搞cocos2dx的lua脚本,话说lua这东西几年前学过一段时间,也自己开发过c++接口,做过一些小东西,不过时间久远,记忆模糊。捡起来还是费了点功夫,下面就是我的一些体会。

cocos2dx使用的是tolua++来制作的lua接口,tolua++文档不多,网上的一些文章也是答非所问,所以自己看代码是最佳学习途径。

cocos2dx操作lua的类是CCLuaEngine,其中实现了加载与实行lua脚本,以及操作lua stack。

LuaCocos2d.cpp很主要,文件的开头注释也说明其是由tolua++自动生成的,我们想在lua中操作自己定义的类就是通过修改此文件实现的,两个重要函数是void tolua_reg_types (lua_State* tolua_S)与int tolua_Cocos2d_open (lua_State* tolua_S),前者是注册自定义类型,后者是定义其接口,调用关系是tolua_Cocos2d_open调用tolua_reg_types,而tolua_Cocos2d_open是在CCLuaEngine的init中调用的。

假设我要向lua注册新类,那么首先我要在tolua_reg_types中添加一行注册代码,然后在tolua_Cocos2d_open添加其接口说明,我将这两个步骤定义成两个函数,单独在一个文件中实现,文件名为cwLuaReg.cpp,内容为:
#include "cwLuaReg.h"

#include "cwGameObject.h"
#include "cwCollisionObject.h"
#include "cwGravityObject.h"

#ifdef __cplusplus

static int tolua_collect_cwGameObject(lua_State* tolua_S)
{
      cwGameObject* self = (cwGameObject*) tolua_tousertype(tolua_S,1,0);
      delete self;
      return 0;
}

static int tolua_collect_cwGravityObject(lua_State* tolua_S)
{
      cwGravityObject* self = (cwGravityObject*) tolua_tousertype(tolua_S,1,0);
      delete self;
      return 0;
}

#ifndef TOLUA_DISABLE_tolua_cw_GameObject_create00
static int tolua_cw_GameObject_create00(lua_State* tolua_S)
{
      tolua_Error tolua_err;
      if(!tolua_isusertable(tolua_S,1,"cwGameObject",0,&tolua_err) ||
            !tolua_isnoobj(tolua_S,2,&tolua_err))
            goto tolua_lerror;
      else
      {
            {
                  cwGameObject* tolua_ret = (cwGameObject*)  cwGameObject::create();
                  int nID = (tolua_ret) ? (int)tolua_ret->m_uID : -1;
                  int* pLuaID = (tolua_ret) ? &tolua_ret->m_nLuaID : NULL;
                  toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret,"cwGameObject");
            }
      }
      return 1;
tolua_lerror:
      return 0;
}
#endif //#ifndef TOLUA_DISABLE

#ifndef TOLUA_DISABLE_tolua_cw_GameObject_getSpeed00
static int tolua_cw_GameObject_getSpeed00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
      tolua_Error tolua_err;
      if (!tolua_isusertype(tolua_S,1,"cwGameObject",0,&tolua_err) ||
            !tolua_isnoobj(tolua_S,2,&tolua_err))
            goto tolua
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值