C語言讀取LUA表----Read lua-table in C API


在C/C++中使用C api讀取lua表

假設lua表內容為

global = "g"

那么很容易我們可以使用獲取全局變量的API

lua_getglobal

去獲取全局變量的值

 

然而游戲中大部分情況下

配表文件中並沒有全局變量

比如如下配表

local t = {a = "A" , b = "B"}
return t

讀取這樣的配表

需要更加復雜的操作

包括如下幾點

1.load文件后執行編譯后的函數得到返回table

2.lua_next遍歷table

3.處理table嵌套table的情況(二維數組)

 

1.load文件后執行編譯后的函數得到返回table

int luaL_dofile (lua_State *L, const char *filename);

Loads and runs the given file. It is defined as the following macro:

     (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))

It returns 0 if there are no errors or 1 in case of errors.

以上是最直接的方法

LUA_MULTRET宏值為-1

表示lua文件返回結果全部壓棧

luaL_dofile從其定義我們可以看出,先加載后執行文件

以下則是具體的加載定義

int lua_load (lua_State *L,
              lua_Reader reader,
              void *data,
              const char *chunkname);

Loads a Lua chunk. If there are no errors, lua_load pushes the compiled chunk as a Lua function on top of the stack. Otherwise, it pushes an error message.

This function only loads a chunk; it does not run it.

int luaL_loadfile (lua_State *L, const char *filename);

Loads a file as a Lua chunk. This function uses lua_load to load the chunk in the file named filename. If filename is NULL, then it loads from the standard input. The first line in the file is ignored if it starts with a #.

This function returns the same results as lua_load, but it has an extra error code LUA_ERRFILE if it cannot open/read the file.

As lua_load, this function only loads the chunk; it does not run it.

 

當luaFunction被push到棧頂之后,lua_pcall執行它就可以得到表(return值在棧頂)

lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);

一般來說lua_pcall(state , 0--[[0個參數]] , 1--[[1個返回值]] , 0)即可

成功執行后return的table在棧頂

 

2.lua_next遍歷table

int lua_next (lua_State *L, int index);

Pops a key from the stack, and pushes a key-value pair from the table at the given index (the "next" pair after the given key). If there are no more elements in the table, then lua_next returns 0 (and pushes nothing).

/* table is in the stack at index 't' */
     lua_pushnil(L);  /* first key */
     while (lua_next(L, t) != 0) {
       /* 'key' is at index -2 and 'value' at index -1 */
       printf("%s - %s\n",
         lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1)));
       lua_pop(L, 1);  /* removes 'value'; keeps 'key' for next iteration */
     }

lua_next非常奇葩,完全是面向過程的

非常機械化的先pop棧頂元素,再或push一個keyValue-pair from table(if exist)

首先pushnil是為了防止首次lua_next時pop掉不該pop的東西

之后在循環內部手動pop一次,就可以保持循環(先pop1個,再push2個,再pop1個)

當循環結束時,棧頂元素不變

 

3.處理table嵌套table的情況(二維數組)

略(lua_type獲得value的類型,如果類型是table則遞歸處理存儲table中的值)

 

 

參考文獻

http://manual.luaer.cn/

http://book.luaer.cn/

http://xxnull.blog.163.com/blog/static/176398157201181991147848/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM