Lua在遊戲開發中應用是本文要介紹的內容,主要是來瞭解並學習lua中遊戲的開發,具體內容的實現,來看本文詳解。
前些日子一直忙於開發BigTank項目(參見劣質設計網站:http://www.buaa-mstc.com,不支援IE),總結了一些Lua在C#項目中的應用方法。
Lua 是一個小巧的指令碼語言。作者是巴西人。該語言的設計目的是為了嵌入應用程式中,從而為應用程式提供靈活的擴充和定製功能。它的首頁是 www.lua.org。
Lua指令碼可以很容易的被C/C++代碼調用,也可以反過來調用C/C++的函數,這使得Lua在應用程式中可以被廣泛應用。不僅僅作為擴充指令碼,也可以作為普通的設定檔,代替XML,Ini等檔案格式,並且更容易理解和維護。
在C#中使用Lua也十分簡單。
- LuaInterface is a library for integration between the Lua language and Microsoft
- .NET platform’s Common Language Runtime (CLR). Lua scripts can use it to instantiate CLR objects,
- access properties, call methods, and even handle events with Lua functions.
從LuaInterface網站上可以下載到這個庫。在你的項目中引用LuaInterface.dll後就可以開始了。
BigTank項目還沒有確定是否要開源,所以我拿自己寫的電子寵物程式示範一下它也用了Lua,你可以在實驗室頁面找到它的全部原始碼)。
- C#:
-
- //...
- /// <summary>
- /// Lua虛擬機器
- /// </summary>
- private static Lua luaVM = null;
-
- /// <summary>
- /// 寵物的建構函式
- /// </summary>
- public Pet(PetForm _petForm, string _petName, string _petPath)
- {
- petState = new PetState();
- petForm = _petForm;
- petName = _petName;
-
- //構造Lua虛擬機器以解析寵物AI
- luaVM = new Lua();
- //註冊提供給寵物AI的API函數
- Type tThis = this.GetType();
- luaVM.RegisterFunction("PetDo", this, tThis.GetMethod("LuaPetDo"));
- luaVM.RegisterFunction("PetDoFrame", this, tThis.GetMethod("LuaPetDoFrame"));
- luaVM.RegisterFunction("Sleep", this, tThis.GetMethod("LuaSleep"));
- //載入AI檔案
- luaVM.DoFile(System.AppDomain.CurrentDomain.BaseDirectory + _petPath + "\\ai.lua");
- }
其中RegisterFunction作用是註冊C#代碼中的一個public(最新版本的LuaInterface支援private)函數來供Lua指令碼使用,其中無需關心參數的個數以及類型。
- Lua:
- PetDo("Sleep");
執行DoFile後會調用Lua指令碼,後者則調用C#中的PetDo函數完成指定動作。
小結:Lua在遊戲開發中應用教程的內容介紹完了,希望通過本文的學習能對你有所協助!