c/c++解析lua配置文件

lua是一個開源的可嵌入腳本語言,他的官方網站 http://www.lua.org/

lua腳本除了可以用來執行外,還可以做爲配置文件,同時用C API來解析。比如在遊戲裏比較常見。

 

在 C/C++中解析lua有以下步驟如下:

1. 包含lua頭文件,如果是C++程序,需要聲明 extern c

1 extern C
2 {
3     #include "lua.h"
4     #include "lualib.h"
5     #include "lauxlib.h"
6 };

 

2. 創建lua_State, 打開lua標準庫

1 lua_State* L = luaL_newstate();
2 luaL_openlibs(L);

 

3. 載入和運行lua配置文件

1 luaL_loadfile(L, "scene.lua");
2 lua_pcall(L, 0, LUA_MULTRET, 0);
3 
4 //或者直接調用lua_dofile來完成載入和運行
5 //luaL_dofile(L, "scene.lua");

 

4. 讀取配置文件內容。 lua跟C/C++的數據交換通過棧來進行。C/C++ 通過lua的API函數從lua_State中讀取數據並壓入棧中,然後再讀取棧中的數據, 最後再把數據從棧中pop出來.

複製代碼
 1 lua_getfeild(L,idx, key);  //push t[k] onto the stack, where t is the value at the given valid index
 2 
 3 // or get the global value and push it on to the stack, as below
 4 // lua_getglobal(L, key); // push onto the stack the value of the global key
 5 
 6 // read data from the stack
 7 const char* str = lua_tostring(L,-1);
 8 //or
 9 // int b = lua_toboolean(L,-1);
10 //or other data types
11 // ...
12 
13 lua_pop(L, 1);
複製代碼

  如果lua配置文件裏的數據是嵌套定義的, 那麼就需要嵌套執行上面的程序段,把數據讀出來.

  如果是有很多相同類型的數據集合,就需要不斷把數據壓入棧中讀取, 比如:

複製代碼
 1 lua_pushnil(L);
 2 while(lua_next(L, -2))
 3 {
 4     lua_getfeild(L, -1, key);
 5 
 6     // read data from the stack
 7     const char* str = lua_tostring(L,-1);
 8     //or
 9     // int b = lua_toboolean(L,-1);
10     //or other data types
11     // ...
12 
13     lua_pop(L, 1);    
14 }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章