詳解LUA 5.1編譯及實例操作
LUA 5.1編譯及實例操作是本文要介紹的內容,以前沒接觸過,并且能找的資料也少之又少, 花了兩天的時間才搞定..一般的都是在vs2005中開發(我的就是),以下是關于vs2005中使用lua。
以下是我在vs2005中編譯方法:
1、打開vs命令行工具、 工具->visual studio 2005 command prompt
2、到lua-5.1的目錄也就是etc的上一級目錄 :cd/d d:\lua-5.1
3、執行:etc\luavs.bat(注意:這里是\,不是/)
4、然后lua51.dll ,lua51.lib,lua.exe就生成在src路徑下了~(注意因為是lua5.1的所以沒有luac.exe,以前的版本有)
因為在vs2005中lua是外來的,所以要讓vs2005能找到lua的頭文件和庫文件(lua5.1中只有一個lua51.lib),在vs中包含,于是:工具->選項->項目和解決方案->vc++ 目錄 右邊選擇包含文件把src的路徑包含進來(關于頭文件的)。
還有庫文件同意的操作,不過這里就是后來一直出錯的點,這里這種方式包含的庫文件是包含不進來的,后面講到的一種方法可正確包含
頭文件和庫文件都包含進來后就可以在c++中使用lua了
看一個實例如下:
- #include <stdio.h>
- #include <iostream>
- extern "C"
- {
- #include "lua.h"
- #include "lualib.h"
- #include "lauxlib.h"
- }//在工具中包含文件的那個~~
- /* Lua解釋器指針 */
- lua_State * L;
- #pragma comment(lib,"lua51.lib")//包含庫文件~~在工具里包含不進來,上面的包含不進來的處理辦法是:
- //把lua51.dll 拷到項目的dubug目錄下,把lua51.lib拷到項目目錄的項目名的文件夾下
- int main ()
- {
- /* 初始化Lua */
- L = lua_open();
- /* 載入Lua基本庫 */
- luaL_openlibs(L);
- /* 運行腳本 ,注意路徑*/
- luaL_dofile(L, "d:\\test.lua");
- /* 清除Lua */
- lua_close(L);
- //printf( "Press enter to exit…" );
- //getchar();
- return 0;
- }
上面是c++的一個空工程
下面是test.lua的代碼:是一個石頭剪子布的小的游戲實例
代碼如下:
- ---[[
- math.randomseed(os.time()) --[[為隨機數產生器生成一個種子--]]
- user_score = 0
- comp_score = 0 -- 全局變量存分數
- lookup = {}; --輸贏對照表
- lookup["rock"]={rock = "draw",paper = "lose",scissors ="win"}
- lookup["paper"]={rock = "win",paper = "draw",scissors = "lose"}
- lookup["scissors"]={rock = "lose",paper = "win",scissors = "draw"}
- function GetAiMove() --Ai的函數
- local int_to_string = {"rock","paper","scissors"} --局部一個table,對照用
- return int_to_string[math.random(3)]
- end
- function EvaluateTheGuess(user_guess,comp_guess) -- 計算結果的函數
- if(lookup[user_guess][comp_guess]=="win") then
- print ("user win the game")
- --print()
- user_scoreuser_score=user_score+1 --小錯誤 ~已改
- elseif (lookup[user_guess][comp_guess]=="lose") then
- print ("user lose the game")
- --print()
- comp_scorecomp_score=comp_score+1
- else
- print ("draw!")
- --print()
- end
- end
下面開始
- print ("game begin:enter q to guit game")
- --print() --換行?
- loop = true
- while loop==true do
- --print()
- print("user: "..user_score.." comp: "..comp_score)
- print()
- print("p--布 r--拳頭 s--減")
- print("請輸入:")
- --io.open()
- user_guess =io.stdin:read '*l' --出錯的地方,這里是l不是1
- --user_guess = "r"
- print()
- local letter_to_string = {r="rock",s="scissors",p="paper"} --亦是局部的一個table 對照用的
- if(user_guess == "q") then
- loop = false
- elseif(user_guess == "r") or (user_guess == "s") or(user_guess =="p") then
- comp_guess=GetAiMove()
- EvaluateTheGuess(letter_to_string[user_guess],comp_guess)
- else
- print ("invalid input,try again")
- end
- end
- --]]
小結:關于詳解LUA 5.1編譯及實例操作的內容介紹完了,希望通過本文的學習能對你有所幫助!