轉自:http://www.cnblogs.com/Zackzhang/p/5093329.html
一、lua環境的搭建
-
建議去網上下載下傳luaforwindow,這是一款跟衆多window系統的軟體一樣,安裝起來簡單友善,一路點next就能搞定了。而且他還包含了有用的與lua有關的基本工具
他包括以下元件:
Lua與C++互動初探之C++調用Lua Lua(Command Line):lua的一個指令行編輯器。簡單輕便,習慣指令行編(zhuang)輯(bi)的可以試試。
Lua Examples: 包含lua使用的一些例子。
LuaForWindows Documentation :LuaForWindows這款軟體的一些說明
QuickLuaTour : lua快速入門向導,沒什麼用,看看就好
SciTE:lua的一個不錯的文本編輯器。可以在裡面測試一些lua代碼,可以運作測試。前提是要先儲存檔案在運作,否則他沒有任何反應。别問我是怎麼知道的,心塞塞
Documentation:裡面包含lua的幫助文檔,最有用的就是他了吧。
安裝好後Lua的環境就算是搭建好了。我們用指令行簡單來測試一下:
Ok,木有問題
二、VS環境配置
- 這一步是最重要的,一開始我是去lua官網下載下傳的源檔案再把他們添加到vs項目,雖然編譯是沒有問題了,但是在測試運作的時候連結還是出現了問題。很明顯我是少了什麼東東。後來我改用下面的方法解決了問題。
- 選中項目,右鍵->屬性->定位到VC++目錄項
Lua與C++互動初探之C++調用Lua - 在"可執行檔案目錄"裡添加上lua的安裝目錄。過程如下:
Lua與C++互動初探之C++調用Lua Lua與C++互動初探之C++調用Lua 定位到Lua的安裝檔案夾,我的是:Lua與C++互動初探之C++調用Lua 确定後傳回Lua與C++互動初探之C++調用Lua - 用同樣的步驟,将"lua安裝目錄\5.1\include"添加到"包含目錄";
- 将"lua安裝目錄\5.1\lib"添加到"庫目錄";
- 跳到"連接配接器"的"輸入"欄。将"附加依賴項"中添加上"lua51.lib;lua5.1.lib";
Lua與C++互動初探之C++調用Lua 現在我們用代碼測試一遍:Lua與C++互動初探之C++調用Lua
#include "stdafx.h"
#include <iostream>
#include <string.h>
using namespace std;
extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
void main()
{
//1.建立一個state
lua_State *L = luaL_newstate();
//2.入棧操作
lua_pushstring(L, "Hello World~");
//3.取值操作
if (lua_isstring(L, 1)) { //判斷是否可以轉為string
cout << lua_tostring(L, 1) << endl; //轉為string并傳回
}
//4.關閉state
lua_close(L);
system("pause");
return;
}
是不是木有問題啦╮(╯▽╰)╭
喏,我們親愛的World君
-
Lua與C++的互動測試
上面我們已經把需要的環境什麼的都配置好了,現在重頭戲上場( ̄︶ ̄)
- 我們建一個test.lua檔案;
function Communicate(name) return ("Hello "..name..", I`m in Lua"); end
- 我們調用lua檔案的cpp代碼
#include "stdafx.h"
#include <iostream>
#include <string.h>
using namespace std;
extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
void main()
{
string hello = "This is Zack, I`m in C++";
cout << hello.c_str() << endl;
//建立Lua狀态
lua_State *L = luaL_newstate();
if (L == NULL)
{
return;
}
//加載Lua檔案
int bRet = luaL_loadfile(L, "test.lua");
if (bRet)
{
cout << "load file error" << endl;
return;
}
//運作Lua檔案
bRet = lua_pcall(L, 0, 0, 0);
if (bRet)
{
cout << "pcall error" << endl;
return;
}
//讀取函數
lua_getglobal(L, "Communicate"); // 擷取函數,壓入棧中
lua_pushstring(L, "Zack"); // 壓入參數
int iRet = lua_pcall(L, 1, 1, 0);// 調用函數,調用完成以後,會将傳回值壓入棧中,第一個1表示參數個數,第二個1表示傳回結果個數。
if (iRet) // 調用出錯
{
const char *pErrorMsg = lua_tostring(L, -1);
cout << pErrorMsg << endl;
lua_close(L);
return;
}
if (lua_isstring(L, -1)) //取值輸出
{
string Result = lua_tostring(L, -1);
cout << Result.c_str() << endl;
}
//關閉state
lua_close(L);
system("pause");
return;
}
結果:
嗯,大功告成。就醬紫了╰( ̄▽ ̄)╮╭(′▽`)╯╰( ̄▽ ̄)╮