LoginSignup
3
3

More than 5 years have passed since last update.

C++からLuaにEventCustomを送る

Last updated at Posted at 2014-08-23

Cocos2d-x/Luaで開発していると、課金の完了や広告のタップなどC++側からLuaにイベントを通知したいことがあります。Luaのグローバル関数を呼び出す場合以下のようになります。

cpp
lua_getglobal(L, "onSomeEvent");
lua_pcall(L, 0, 0, 0);
lua
function onSomeEvent()
    cclog("some event")
end

この方法だとグローバルな関数を定義しなければならず、文脈によってイベントを受け取ったときの処理を変えたい場合などに不便です。カスタムイベントを使うと以下のようになります。

cpp
auto scene = Director::getInstance()->getRunningScene();
scene->getEventDispatcher()->dispatchCustomEvent("onSomeEvent");
lua
local layer = cc.Layer:create()
local listener = cc.EventListenerCustom:create("onSomeEvent", function(event)
    cclog(event:getEventName())
end)
local eventDispatcher = layer:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer)

ただし、イベントにパラメータを持たせることはできないようです。EventCustomは本来任意のuserDataを持てるのですが、Luaオブジェクトからは参照できません。

cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp
int lua_register_cocos2dx_EventCustom(lua_State* tolua_S)
{
    tolua_usertype(tolua_S,"cc.EventCustom");
    tolua_cclass(tolua_S,"EventCustom","cc.EventCustom","cc.Event",nullptr);

    tolua_beginmodule(tolua_S,"EventCustom");
        tolua_function(tolua_S,"new",lua_cocos2dx_EventCustom_constructor);
        tolua_function(tolua_S,"getEventName",lua_cocos2dx_EventCustom_getEventName);
    tolua_endmodule(tolua_S);
    std::string typeName = typeid(cocos2d::EventCustom).name();
    g_luaType[typeName] = "cc.EventCustom";
    g_typeCast["EventCustom"] = "cc.EventCustom";
    return 1;
}
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3