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


cococs2dx 3.13.1 + vs2013 + win10

1.首先按照《cocos2dx lua 绑定之一:自动绑定自定义类》绑定Student类

 

2.在Student类中增加一个用于测试手动绑定的函数manual_call

①Student.h中增加函数

    //手动绑定调用函数
    void manual_call();

②Student.cpp中增加函数实现

//和自动绑定相比,只增加了这个函数
void Student::manual_call() { std::cout << " manual call function " << std::endl; }

 

3.在libluacocos2d项目中新增两个手动绑定的处理文件lua_cocos2dx_student_manual.h和lua_cocos2dx_student_manual.cpp

 

①lua_cocos2dx_student_manual.h

#pragma once #ifdef __cplusplus extern "C" { #endif #include "tolua++.h" #ifdef __cplusplus } #endif TOLUA_API int register_student_moudle(lua_State* L);

 

②lua_cocos2dx_student_manual.cpp

#include "scripting/lua-bindings/manual/user_define/lua_cocos2dx_student_manual.hpp" #include "scripting/lua-bindings/auto/lua_userdefine_student_auto.hpp" #include "user_define/Student.h" #include "scripting/lua-bindings/manual/tolua_fix.h" #include "scripting/lua-bindings/manual/LuaBasicConversions.h" #include "scripting/lua-bindings/manual/cocos2d/LuaScriptHandlerMgr.h" #include "scripting/lua-bindings/manual/CCLuaValue.h" #include "scripting/lua-bindings/manual/CCLuaEngine.h" #include "base/CCEventListenerFocus.h"

//调用函数
static int tolua_student_test_function(lua_State* L) { if (nullptr == L) return 0; Student** s = (Student**)luaL_checkudata(L, 1, "Student"); luaL_argcheck(L, s != NULL, 1, "invalid user data"); (*s)->manual_call(); return 0; } //注册函数
static void regist_student_manual_functions(lua_State* L) { //找到对应自动注册的类
    lua_pushstring(L, "Student"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { tolua_function(L, "manual_call", tolua_student_test_function); //将函数绑定到Student类中
 } lua_pop(L, 1); } int register_student_moudle(lua_State* L) { lua_getglobal(L, "_G"); if (lua_istable(L,-1))//stack:...,_G,
 { register_all_userdefine_student(L); regist_student_manual_functions(L); } lua_pop(L, 1); return 1; }

 

4.将函数注册到lua中,找到libluacocos2d项目中

①在CCLuaStack.cpp文件增加头文件引用

#include "scripting/lua-bindings/manual/user_define/lua_cocos2dx_student_manual.hpp"

②在init函数里增加函数注册到Lua

先屏蔽注册自动函数的相关代码,使用register_student_moudle同时注册自动绑定和手动绑定的函数

//register_all_userdefine_student(_state);
register_student_moudle(_state);

 

5.重新编译项目,在Lua里使用

local student = Student:new() student:manual_call()

 

6.如果不使用自动绑定,全部使用手动绑定,可参考下面两篇文章直接进行绑定

 

Lua和C++交互 学习记录之八:C++类注册为Lua模块

Lua和C++交互 学习记录之九:在Lua中以面向对象的方式使用C++注册的类

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM