1. lua源碼下載
去官網http://www.lua.org/download.html下載
2. 使用lua
a)解壓包,將源碼拷貝出來添加進vs工程
b)項目工程代碼只需要包含lua.hpp即可,衝突的main函數更改個名字即可,所有的.c文件設置不使用預編譯頭
3. lua示例
mystr = "hello world"
my_table = {name = "yxli8", id = 123456}
function a_add_b(a,b)
return a+b
end
- c++源碼
#include <iostream>
#include "lua.hpp"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
// 初始化
lua_State *L = luaL_newstate();
if (L == nullptr)
{
return -1;
}
// 加載相關庫文件
luaL_openlibs(L);
// 加載lua文件
int bRet = luaL_loadfile(L, "test.lua");
if (bRet)
{
cout << "load test.lua file failed" << endl;
return -1;
}
// 執行lua文件
bRet = lua_pcall(L, 0, 0, 0);
if (bRet)
{
cout << "call test.lua file failed" << endl;
return -1;
}
// 獲取值
lua_getglobal(L, "mystr");
std::string str = lua_tostring(L, -1);
cout << "str=" << str << endl;
// 獲取表中數據
lua_getglobal(L, "my_table");
lua_getfield(L, -1, "name");
str = lua_tostring(L, -1);
cout << "table:name=" << str << endl;
// 獲取表中數據
lua_getglobal(L, "my_table");
lua_getfield(L, -1, "id");
int nNumber = lua_tonumber(L, -1);
cout << "table:id=" << nNumber << endl;
// 獲取並調用函數
lua_getglobal(L, "a_add_b");
lua_pushnumber(L, 10);
lua_pushnumber(L, 20);
int iRet = lua_pcall(L, 2, 1, 0);
if (iRet)
{
const char* pErrorMsg = lua_tostring(L, -1);
cout << pErrorMsg << endl;
lua_close(L);
return -1;
}
// 獲取結果
if (lua_isnumber(L, -1))
{
double fValue = lua_tonumber(L, -1);
cout << "a + b = " << fValue << endl;
}
lua_close(L);
// waiting for console
cin.get();
return 0;
}
- 備註
lua和c++是通過一個虛擬棧來交互的。
c++調用lua實際上是:由c++先把數據放入棧中,由lua去棧中取數據,然後返回數據對應的值到棧頂,再由棧頂返回c++。
lua調c++也一樣:先編寫自己的c模塊,然後註冊函數到lua解釋器中,然後由lua去調用這個模塊的函數。
在lua中,lua堆棧就是一個struct,堆棧索引的方式可是是正數也可以是負數,區別是:正數索引1永遠表示棧底,負數索引-1永遠表示棧頂