lua table操作例項詳解

2022-04-28 23:57:13 字數 1864 閱讀 4020

lua_gettable

lua_getglobal(l, "mytable") <== push mytable

lua_pushnumber(l, 1)        <== push key 1

lua_gettable(l, -2)         <== pop key 1, push mytable[1]

lua_settable

lua_getglobal(l, "mytable") <== push mytable

lua_pushnumber(l, 1)        <== push key 1

lua_pushstring(l, "abc")    <== push value "abc"

lua_settable(l, -3)         <== mytable[1] = "abc", pop key & value

lua_rawget

:用法同lua_gettable,但更快(因為當key不存在時不用訪問元方法

__index

)

lua_rawset

:

用法同lua_settable,但更快

(因為當key不存在時不用訪問元方法__newindex)

lua_rawgeti

必須為數值鍵

lua_getglobal(l, "mytable") <== push mytable

lua_rawgeti(l, -1, 

1)       <== 

push mytable[1],作用同下面兩行呼叫

--lua_pushnumber(l, 1)      <== push key 1

--lua_

rawget

(l,-2)          <== pop key 1, push mytable[1]

lua_rawseti必須為數值鍵

lua_getglobal(l, "mytable") <== push mytable

lua_pushstring(l, "abc")    <== push value "abc"

lua_rawseti(l, -2, 1)       <== mytable[1] = "abc", pop value "abc"

lua_getfield

必須為字串鍵

lua_getglobal(l, "mytable") <== push mytable

lua_

getfield

(l, -1, 

"x")    <== 

push mytable["x"],作用同下面兩行呼叫

--lua_pushstring(l, "x")    <== push key "x"

--lua_

gettable

(l,-2)        <== pop key "x", push mytable["x"]

lua_setfield

必須為字串鍵

lua_getglobal(l, "mytable") <== push mytable

lua_pushstring(l, "abc")    <== push value "abc"

lua_setfield(l, -2, "x")    <== mytable["x"] = "abc", pop value "abc"

lua table 的操作 四

table在前面作過介紹,它是一種關聯陣列,這種關聯指的是可以設定各類型別的key來儲存值。為 table a 並設定元素,然後將 a 賦值給 b,則 a 與 b 都指向同乙個記憶體位址 如果 a 設定為 nil 則 b 同樣能訪問 table 的元素。如果沒有指定的變數指向a,lua的垃圾 機制會...

lua table操作及math庫

1 table.concat table sep start end concat是concatenate 連鎖,連線 的縮寫.table.concat 函式列出引數中指定table的陣列部分從start位置到end位置的所有元素,元素間以指定的分隔符 sep 隔開。2table.insert ta...

Lua Table介紹與基礎操作

table是lua的一種資料結構用來幫助我們建立不同的資料型別 可以用任意型別的值來作陣列的索引,但這個值不能是 nil。不固定大小的,你可以根據自己需要進行擴容。table常用操作 構造器是建立和初始化表的表示式。表是lua特有的功能強大的東西。最簡單的建構函式是 用來建立乙個空表。初始化陣列 t...