Skip to content

Instantly share code, notes, and snippets.

@stevetranby
Created March 29, 2012 05:49
Show Gist options
  • Save stevetranby/2233787 to your computer and use it in GitHub Desktop.
Save stevetranby/2233787 to your computer and use it in GitHub Desktop.
call lua functions from c++ using with Cocos2dx
// register lua engine
CCScriptEngineProtocol* pEngine = CCLuaEngine::engine();
CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);
string filename = "hello3.lua";
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
unsigned long size;
char *pFileContent = (char*)CCFileUtils::getFileData("hello.lua", "r", &size);
if (pFileContent)
{
// copy the file contents and add '\0' at the end, or the lua parser can not parse it
char *pCodes = new char[size + 1];
pCodes[size] = '\0';
memcpy(pCodes, pFileContent, size);
delete[] pFileContent;
pEngine->executeString(pCodes);
delete []pCodes;
}
#endif
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE)
string path = CCFileUtils::fullPathFromRelativePath(filename.c_str());
pEngine->addSearchPath(path.substr(0, path.find_last_of("/")).c_str());
pEngine->executeScriptFile(path.c_str());
#endif
CCLOG("running scripts");
//test2p
lua_State *L = pEngine->getLuaState();
lua_getglobal(L, "test");
lua_call(L, 0, 0);
lua_getglobal(L, "test1r");
lua_call(L, 0, 1);
int ret = lua_tointeger(L, -1);
CCLOG("ret=%d",ret);
lua_getglobal(L, "test2p");
lua_pushstring(L, "This is an argument passed to a Lua function from C/C++");
lua_pushstring(L, "Arg 2");
lua_call(L, 2, 0);
lua_getglobal(L, "test1p2r");
lua_pushinteger(L, 3);
lua_call(L, 1, 2);
int x = lua_tointeger(L, -2);
const char *y = lua_tostring(L, -1);
CCLOG("val=%d",x);
CCLOG("msg=%s",y);
return true;
@einverne
Copy link

How can I set up the build environment? my project cannot find the lualib.h ....

@einverne
Copy link

New version cocos2d-x there is no function called getLuaState() in class CCLuaEngine.h

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment