您的位置:首页 > 编程语言 > Lua

Lua注册回调到C++

2016-04-12 17:39 916 查看
http://cn.cocos2d-x.org/tutorial/show?id=1896

思路

像所有语言一样,绑定回调主要是执行的任务执行到特定情形的时候,调用对用回调方法。本文也一样,Lua注册回调到C++的核心思路是,当C代码执行到特定特定情形的时候,调用Lua的方法。

我这里使用的是用lua_stack直接调用lua的方法,没有使用Cocos2d-x封装的那个dispatcher,因为熟悉那个格式太墨迹了。

主要步骤如下

C代码绑定回调,调用Lua函数

1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
ArmatureNode::registerMovementEventHandler(
handler)

{
//移除之前注册的监听

//缓存lua函数的引用这个后边说


autof=[
](cocos2d::EventCustom*event)
{

autotype=(
)eventData->getType();

autolastState=eventData->armature->getAnimation()->getLastAnimationState();

stack->pushObject(
,
);

stack->pushString(movementId.c_str(),movementId.size());
stack->executeFunctionByHandler(_movementHandler,3);
dispatcher->addCustomEventListener(dragonBones::EventData::COMPLETE,f);
}
void
void
if
{

//移除lua函数的绑定

}
}

2
4
6
8
10
12
14
16
18
20
tolua_db_DBCCArmature_registerMovementEventHandler(lua_State*tolua_S)

{
(NULL==tolua_S)

0;

argc=0;


self=
<dragonBones::ArmatureNode*>(tolua_tousertype(tolua_S,1,0));
argc=lua_gettop(tolua_S)-1;


(1==argc)

//第二个参数,就是Lua里的function这里要通过toluafix_ref_function这个函数映射成一个Int值
handler=(toluafix_ref_function(tolua_S,2,0));

return
}

0;

}
2
4
6
8
10
12
14
intlua_pushstring(tolua_S,
);
lua_rawget(tolua_S,LUA_REGISTRYINDEX);

(lua_istable(tolua_S,-1))

lua_pushstring(tolua_S,
);

lua_rawset(tolua_S,-3);
lua_pop(tolua_S,1);
0;

}

2
4
6
8
"Dragon"
localanimation=arm:getAnimation()
"walk"
arm:registerMovementEventHandler(
print(...)
)

-测试

打印回调输出,测试通过userdata8walk

其他

2
4
6
8
10
12
14
16
18
20
22
int
int
int
if
return
s_function_ref_id++;
lua_pushstring(L,TOLUA_REFID_FUNCTION_MAPPING);
lua_rawget(L,LUA_REGISTRYINDEX);
lua_pushinteger(L,s_function_ref_id);
lua_pushvalue(L,lo);

lua_rawset(L,-3);
lua_pop(L,1);
s_function_ref_id;

}
TOLUA_API
toluafix_get_function_by_refid(lua_State*L,
refid)

{
//存放luafunction映射table的key压栈

//获取方法映射表,放在栈顶

//function_id压栈

//获取到的luafunction放到栈顶

//

}
<ullist-paddingleft-2"=""style="word-wrap:break-word;">

executeFunctionByHandler

executeFunctionByHandler这个方法只是通过toluafix_get_function_by_refid获取到function然后通过lua_pcall方法调用,代码就不写了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: