Lua在遊戲開發中應用教程

來源:互聯網
上載者:User

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也十分簡單。

 
  1. LuaInterface is a library for integration between the Lua language and Microsoft   
  2. .NET platform’s Common Language Runtime (CLR). Lua scripts can use it to instantiate CLR objects,   
  3. access properties, call methods, and even handle events with Lua functions. 

從LuaInterface網站上可以下載到這個庫。在你的項目中引用LuaInterface.dll後就可以開始了。

BigTank項目還沒有確定是否要開源,所以我拿自己寫的電子寵物程式示範一下它也用了Lua,你可以在實驗室頁面找到它的全部原始碼)。

 
  1. C#:  
  2.  
  3. //...  
  4. /// <summary> 
  5. /// Lua虛擬機器  
  6. /// </summary> 
  7. private static Lua luaVM = null;  
  8.    
  9. /// <summary> 
  10. /// 寵物的建構函式  
  11. /// </summary> 
  12. public Pet(PetForm _petForm, string _petName, string _petPath)  
  13. {  
  14.     petState = new PetState();  
  15.     petForm = _petForm;  
  16.     petName = _petName;  
  17.    
  18.     //構造Lua虛擬機器以解析寵物AI  
  19.     luaVM = new Lua();  
  20.     //註冊提供給寵物AI的API函數  
  21.     Type tThis = this.GetType();  
  22.     luaVM.RegisterFunction("PetDo", this, tThis.GetMethod("LuaPetDo"));  
  23.     luaVM.RegisterFunction("PetDoFrame", this, tThis.GetMethod("LuaPetDoFrame"));  
  24.     luaVM.RegisterFunction("Sleep", this, tThis.GetMethod("LuaSleep"));  
  25.     //載入AI檔案  
  26.     luaVM.DoFile(System.AppDomain.CurrentDomain.BaseDirectory + _petPath + "\\ai.lua");  

其中RegisterFunction作用是註冊C#代碼中的一個public(最新版本的LuaInterface支援private)函數來供Lua指令碼使用,其中無需關心參數的個數以及類型。

 
  1. Lua:  
  2. PetDo("Sleep"); 

執行DoFile後會調用Lua指令碼,後者則調用C#中的PetDo函數完成指定動作。

小結:Lua遊戲開發中應用教程的內容介紹完了,希望通過本文的學習能對你有所協助!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.