我们可以在lua上面编写cocos2dx 用lua调用到cocos2dx的api 是因为在
lua_cocos2dx_auto这类函数里面建立的连接,大家可以参考然后自己写做连接。
如我一下建立一个类 如building
class Building : public Node
{
public:
Building(const std::string &fileName);
static Building* create(const std::string &fileName);
void setSelected(bool selected);
void setPosition(float x, float y);
我自己再仿照lua_cocos2dx_auto建立连接,如下
在
TOLUA_API int register_all_classes(lua_State* tolua_S)
函数里面写
lua_register_Building(tolua_S);
这里是实现
int lua_register_Building(lua_State* tolua_S)
{
tolua_usertype(tolua_S,"Building");
tolua_cclass(tolua_S,"Building","Building","cc.Sprite",NULL);
tolua_beginmodule(tolua_S,"Building");
tolua_function(tolua_S,"create", lua_Building_create);
这里是实现
lua_Building_create 等各个函数
int lua_Building_create(lua_State* tolua_S)
{
int argc = lua_gettop(tolua_S)-1;
if (argc != 1) {
CCLOG("%s, %d+++++++++++argc error :%d", __FUNCTION__, __LINE__, argc);
return 0;
}
std::string arg0;
if (luaval_to_std_string(tolua_S, 2, &arg0) == false) //栈里总共两个元素,第2个和第-1个都是一样的
{
CCLOG("%s, %d+++++++++++get argc error", __FUNCTION__, __LINE__);
return 0;
}
Building* ret = Building::create(arg0);
if (NULL != ret)
{
std::string className = "BayuArmature";
cocos2d::Object *dynObject = dynamic_cast<cocos2d::Object *>((Building*)ret);
if (NULL != dynObject)
{
int ID = ret ? (int)(dynObject->_ID) : -1;
int* luaID = ret ? &(dynObject->_luaID) : NULL;
toluafix_pushusertype_ccobject(tolua_S,ID, luaID, (void*)ret, className.c_str());
}
else
{
tolua_pushusertype(tolua_S, (void*)ret, className.c_str());
}
}
else
{
lua_pushnil(tolua_S);
}
return 1;
}
最后在AppDelegate函数钟调用
register_all_classes 的函数然后就算是注册成功了。
如下代码
// register lua engine
auto engine = LuaEngine::getInstance();
ScriptEngineManager::getInstance()->setScriptEngine(engine);
register_all_classes(engine->getLuaStack()->getLuaState());
然后就可以在lua调用building类了