2011-07-18 36 views
2

需要創建一些表,所以我可以從它以這種方式得到一個信息:創建的Lua高級表

table[attacker][id] 

如果我將使用

print(table[attacker][id]) 

它應該打印

嘗試過很多辦法,但都沒有找到什麼好的...

我想應該是這樣的......

table.insert(table, attacker, [id] = value) 

^這是行不通的。

有人可以幫助我嗎?


編輯

好吧,當我嘗試這樣說:

x = {} 
function xxx() 
    if not x[attacker][cid] then 
     x[attacker][cid] = value 
    else 
     x[attacker][cid] = x[attacker][cid] + value 
    end 
    print(x[attacker][cid]) 
end 

我得到一個錯誤說: '?'

試圖索引字段(一個零值)

+1

該錯誤的含義正是它所說的......'x [攻擊者]'顯然是'無'。 – Amber

回答

5

你需要花括號創建內表:

table.insert(my_table, attacker, {[id]=value}) 

-- the advantage of this is that it works even if 'attacker' isn't a number 
my_table[attacker] = {[id]=value} 

a = 1 
b = 2 
c = 3 
d = {} 
table.insert(d, a, {[b]=c}) 
print(d[a][b]) -- prints '3' 
+0

這隻有在攻擊者是一個整數時纔有效,因爲table.insert只能將值插入表的數組部分。 –

+0

當然。當然,普通表分配語法也適用於非整數鍵;我只是簡單地將OP的例子應用到最近的事情上。 – Amber

+0

編輯我的問題。 – Lucas

2

什麼是attacker?也就是說,它包含什麼價值?它不是真的與它所包含的內容有關,因爲Lua表可以使用任何Lua值作爲關鍵字。但是知道這很有用。

在任何情況下,它都非常簡單。

tableName = {}; --Note: your table CANNOT be called "table", as that table already exists as part of the Lua standard libraries. 
tableName[attacker] = {}; --Create a table within the table. 
tableName[attacker][id] = value; --put a value in the table within the table. 

在你編輯的問題,是因爲您沒有采取上述步驟2的註釋。一個Lua表中的值在它們有值之前是空的(零)。因此,直到第2行,tableName[attacker]。你不能索引一個零值。因此,您需要必須確保您希望索引的tableName中的任何密鑰實際上都是表格。

換句話說,你不能這樣做tableName[attacker][id],除非你知道type(tableName[attacker]) == "table"爲真。

+0

編輯我的問題 – Lucas

1

你應該使用table = {['key']='value'}使它更容易。