Cocos2d-x Open Source engine is currently very popular in the field of mobile development, I used for a while, very like its Lua binding, Once understood its working mechanism, compared with C ++.
However, it is not easy to use the Lua script. To make Lua binding very easy to use, it may still require a lot of work.
Record a very practical technique here: When Lua calls the cocos2d-x interface and causes a crash, you cannot directly see the Lua call stack, it cannot know which line is currently running to Lua script. The following methods can be considered:
Taking hellolua of cocos2d-x 2.0 as an example, assuming that the Lua script crashes when executing addchild:
File: Hello. Lua
-- Create farmlocal function createlayerfarm () Local layerfarm = cclayer: Create () print (debug. traceback () -- add in farm background local BG = ccsprite: Create ("farm.jpg") BG: setposition (winsize. width/2 + 80, winsize. height/2) layerfarm: release () -- deliberately releases layerfarm, causing exceptions in the C ++ layer when calling addchild. layerfarm: addchild (BG )........
In this way, when addchild is executed, the program will eventually crash due to the NULL pointer. Specifically, the tolua_disable_tolua_cocos2d_ccnode_addchild00 function generated by tolua ++:
/* Method: addchild of class ccnode */# ifndef effecint tolua_cocos2d_ccnode_addchild00 (lua_state * tolua_s) {# ifndef tolua_release tolua_error tolua_err; If (! Tolua_isusertype (tolua_s, 1, "ccnode", 0, & tolua_err) |! Tolua_isusertype (tolua_s, 2, "ccnode", 0, & tolua_err) |! Tolua_isnoobj (tolua_s, 3, & tolua_err) goto tolua_lerror; else # endif {ccnode * Self = (ccnode *) tolua_tousertype (tolua_s, 1, 0 ); ccnode * child = (ccnode *) tolua_tousertype (tolua_s, 2, 0); # ifndef tolua_release if (! Self) tolua_error (tolua_s, "invalid 'self 'in function 'addchild'", null); # endif {// print Lua call stack to start lua_getglobal (tolua_s, "debug "); lua_getfield (tolua_s,-1, "traceback"); int ierror = lua_pcall (tolua_s, // vmachine 0, // argument count 1, // return value count 0 ); const char * SZ = lua_tostring (tolua_s,-1); // The above SZ contains the call stack information of Lua. Make good use of it! Self-> addchild (child) ;}} return 0; # ifndef tolua_release tolua_lerror: tolua_error (tolua_s, "# ferror in function 'addchild '. ", & tolua_err); Return 0; # endif} # endif // # ifndef tolua_disable
As shown in the comments section in the above code, I will not go into details. The principle is two points:
1. During Lua execution, you can call Debug. traceback () to obtain the string describing the call stack at any time.
2. In the preceding example, call Debug. traceback in C. The method for calling the Lua function in C language is the basic content of Lua.