關於C++讀取Lua設定檔實現案例

來源:互聯網
上載者:User

使用C++讀取Lua設定檔實現案例是本文要介紹的內容,主要是來瞭解並學習一下lua設定檔的使用,本文內容主要是以代碼來實現,具體內容來看本文詳解。

 
  1. //LuaEx.h檔案  
  2.  
  3. #pragma once  
  4. #include <Windows.h> 
  5. extern "C"  
  6. {  
  7. #include "lua/lua.h"  
  8. #include "lua/lualib.h"  
  9. #include "lua/lauxlib.h"  
  10. };  
  11.  
  12. class LuaEx  
  13. {  
  14. public:  
  15. LuaEx(void);  
  16. ~LuaEx(void);  
  17. bool LoadFile(LPCSTR str); //載入lua檔案  
  18. LPSTR LoadString(LPCSTR str); //讀取字串  
  19. int LoadInteger(LPCSTR str); //讀取整形  
  20. double LoadDouble(LPCSTR str); //讀取浮點型  
  21. bool LoadBoolean(LPCSTR str); //讀取布爾型  
  22.  
  23. private:  
  24. lua_State *L; //lua指標  
  25. };  
  26.  
  27. //LuaEx.cpp檔案  
  28.  
  29. #include ".\luaex.h"  
  30. #pragma comment(lib, ".\\lua\\lua.lib")  
  31.  
  32. LuaEx::LuaEx(void)  
  33. {  
  34. L = lua_open();  
  35. luaL_openlibs(L);  
  36. }  
  37.  
  38. LuaEx::~LuaEx(void)  
  39. {  
  40. lua_close(L);  
  41. }  
  42.  
  43. bool LuaEx::LoadFile(LPCSTR str)  
  44. {  
  45. if(luaL_dofile(L, str))  
  46. {  
  47. return false;  
  48. }  
  49. return true;  
  50. }  
  51.  
  52. LPSTR LuaEx::LoadString(LPCSTR str)  
  53. {  
  54. lua_getglobal(L, str);  
  55. if (lua_isstring(L, -1))  
  56. {  
  57. return (LPSTR)lua_tostring(L, -1);  
  58. }  
  59. return NULL;  
  60. }  
  61.  
  62. int LuaEx::LoadInteger(LPCSTR str)  
  63. {  
  64. lua_getglobal(L, str);  
  65. if (lua_isnumber(L, -1))  
  66. {  
  67. return (int)lua_tointeger(L, -1);  
  68. }  
  69. return NULL;  
  70. }  
  71.  
  72. double LuaEx::LoadDouble(LPCSTR str)  
  73. {  
  74. lua_getglobal(L, str);  
  75. if (lua_isnumber(L, -1))  
  76. {  
  77. return (double)lua_tonumber(L, -1);  
  78. }  
  79. return 0.0;  
  80. }  
  81.  
  82. bool LuaEx::LoadBoolean(LPCSTR str)  
  83. {  
  84. lua_getglobal(L, str);  
  85. if (lua_isboolean(L, -1))  
  86. {  
  87. return (bool)lua_toboolean(L, -1);  
  88. }  
  89. return false;  

在要使用設定檔的地方執行個體化一個LuaEx類就可以了。

先調用LoadFile載入檔案,參數為檔案路徑。檔案格式可以按照如下方式:

 
  1. title = "遊戲" 
  2. width = 640 
  3. height = 480 
  4. isWindowed = true;  
  5. useSound = false;  
  6. hideMouse = false; 

結尾分號可加可不加,就是寫一個lua指令碼,但是只包含變數不包含方法。

之後就可以讀取其中內容了。例如

 
  1. LoadString("title"); //表示載入變數名為title的變數的值。 

本類中所有函數的參數都是字串。

小結:關於C++讀取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.