| 網(wǎng)站首頁 | 關(guān)于我們 | 開發(fā)優(yōu)勢(shì) | 產(chǎn)品展示 |
| 合作企業(yè) | 新聞動(dòng)態(tài) | 聯(lián)系我們 | 電話聯(lián)系 |
文章作者:濟(jì)南軟件開發(fā) 時(shí)間:2016年11月08日
我們?cè)贚uaWithCPPTest項(xiàng)目下,查看Source.cpp代碼如下:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
extern "C"
{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
};
void TestLua();
int main()
{
TestLua();
return 0;
}
void TestLua()
{
lua_State *L = luaL_newstate();
luaopen_base(L); //
luaopen_table(L); //
luaopen_package(L); //
luaopen_io(L); //
luaopen_string(L); //
luaL_openlibs(L); //打開以上所有的lib
string str;
while (true)
{
cout << "請(qǐng)輸入Lua代碼:" << endl;
getline(cin, str, '\n');
if (luaL_loadstring(L, str.c_str())
|| lua_pcall(L, 0, 0, 0) )
{
const char * error = lua_tostring(L, -1) ;
cout << string(error) << endl;
}
}
lua_close(L);
}
其中,被extern "C"包起來的是lua的主要函數(shù)的聲明。在C++中,每個(gè)嵌入的lua的生命周期與各自的lua_State對(duì)象一一對(duì)應(yīng)。通過luaL_newstate()方法,我們便創(chuàng)建了一個(gè)lua解釋器。隨后的幾個(gè)luaopen_*方法,都是獲取相應(yīng)lua庫的使用權(quán),最后通過luaL_openlibs打開所有的有使用權(quán)的lua標(biāo)準(zhǔn)庫。一切準(zhǔn)備就緒后,我們開始接收輸入。
image
image
image
我們通過luaL_loadstring,將所有代碼讀入lua,并且檢查代碼是否有語法錯(cuò)誤。然后通過lua_pcall,運(yùn)行代碼,將所有的全局變量保存在_G中。通過讀取、運(yùn)行這兩步,我們就建立起一個(gè)自己的lua解釋器了。
將lua作為配置文件
從文件讀取lua代碼,流程與之前的示例一樣,僅是將luaL_loadstring()換成luaL_loadfile()即可。代碼如下:
string str;
while (true)
{
cout << "輸入lua文件路徑:" << endl;
getline(cin, str, '\n');
if (luaL_loadfile(L, str.c_str())
|| lua_pcall(L, 0, 0, 0) )
{
const char * error = lua_tostring(L, -1) ;
cout << string(error) << endl;
return;
}
}
image
image
現(xiàn)在,我們?cè)趌ua中定義變量,并且賦值。然后在c++中取值,運(yùn)算出結(jié)果。在lua文件中,內(nèi)容如下:
image
在c++中,我們獲取a,b兩個(gè)變量的值,然后相加,算出結(jié)果:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
extern "C"
{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
};
void TestLua();
int main()
{
TestLua();
return 0;
}
void TestLua()
{
lua_State *L = luaL_newstate();
luaopen_base(L); //
luaopen_table(L); //
luaopen_package(L); //
luaopen_io(L); //
luaopen_string(L); //
luaL_openlibs(L); //打開以上所有的lib
string str;
while (true)
{
cout << "輸入lua文件路徑:" << endl;
getline(cin, str, '\n');
if (luaL_loadfile(L, str.c_str())
|| lua_pcall(L, 0, 0, 0) )
{
const char * error = lua_tostring(L, -1) ;
cout << string(error) << endl;
return;
}
else
{
break;
}
}
int a = 0;
int b = 0;
// 獲取a的值
lua_getglobal(L, "a");
if (!lua_isnumber(L, -1))
{
cout << "-2 error" << lua_isnumber(L, -1) << lua_isnumber(L, -1) << endl;
return ;
}
a = lua_tonumber(L, -1);
// 獲取b的值
lua_getglobal(L, "b");
if (!lua_isnumber(L, -1))
{
cout << "-1 error" << endl;
return ;
}
b = lua_tonumber(L, -1);
cout << "a = " << a << " b = " << b << endl;
cout << "a + b = " << a + b << endl;
lua_close(L);
}
想要了解更多詳情歡迎來電咨詢18678812288
登陸網(wǎng)址:m.h6244.cn。
聯(lián)系人:王經(jīng)理。