//
// TestScene.cpp
// LuaWithCpp
//
// Created by zctech on 14-3-3.
//
//
#include "TestScene.h"
USING_NS_CC;
using namespace std;
extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
bool TestScene::init()
{
// 1. super init first
if ( !CCLayer::init() )
{
return false;
}
lua_State *pL = lua_open();
luaopen_base(pL);
luaopen_math(pL);
luaopen_string(pL);
string luaPath = CCFileUtils::sharedFileUtils()->fullPathForFilename("my.lua").c_str();
//=====================从lua文件取值===================================
//执行lua脚本
int ret = luaL_dofile(pL, luaPath.c_str());
CCLog("$$$$$$$$$$$$$$$$ open return value : %d", ret);
//重置栈顶索引
lua_settop(pL, 0);
lua_getglobal(pL, "myName");
//判断栈顶的值类型是否为String
ret = lua_isstring(pL, 1);
CCLog("$$$$$$$$$$$$$$$$ is string : %d", ret);
//获取栈顶的值
const char *str = lua_tostring(pL, 1);
CCLog("$$$$$$$$$$$$$$$$ get string : %s", str);
lua_close(pL);
//======================从lua文件取表================================
pL = lua_open();
luaopen_base(pL);
// 执行脚本
luaL_dofile(pL, luaPath.c_str());
// 取得table变量,在栈顶
lua_getglobal(pL, "tb");
// 将C++的字符串放到Lua的栈中,此时,栈顶变为“name”, helloTable对象变为栈底
lua_pushstring(pL, "name");
/*
从table对象寻找“name”对应的值(table对象现在在索引为-2的栈中,也就是当前的栈底),
取得对应值之后,将值放回栈顶
*/
lua_gettable(pL, -2);
// 现在表的name对应的值已经在栈顶了,直接取出即可
const char* sName = lua_tostring(pL, -1);
CCLOG("name = %s", sName);
lua_pushstring(pL, "IQ");
lua_gettable(pL, -3);
int iq = lua_tonumber(pL, -1);
CCLog("IQ = %d", iq);
lua_close(pL);
//====================从lua文件取函数==============================
pL = lua_open();
luaopen_base(pL);
// 执行脚本
luaL_dofile(pL, luaPath.c_str());
//把add函数指针压栈
lua_getglobal(pL, "add");
//把函数参数栈
lua_pushnumber(pL, 1);
lua_pushnumber(pL, 2);
//调用函数
lua_call(pL, 2, 1);
CCLog("add result : %lf", lua_tonumber(pL, -1));
lua_close(pL);
return true;
}
// there's no 'id' in cpp, so we recommend returning the class instance pointer
cocos2d::CCScene* TestScene::scene()
{
// 'scene' is an autorelease object
CCScene *scene = CCScene::create();
// 'layer' is an autorelease object
TestScene *layer = TestScene::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
-- my.lua
myName = "zhangWenChang"
-- 创建一个表
tb = {}
tb.name = "zhangsan"
tb.IQ = 120
-- 创建一个函数
function add(num1, num2)
return (num1 + num2)
end