2015-01-08 66 views
2

我正在嘗試爲MUD創建一個腳本,該腳本將創建一張表以跟蹤每個暴民的平均xp。我在檢查表中元素是否存在以及是否創建它的語法方面遇到了問題。我想是這樣的,但不斷收到:attempt to index field '?' (a nil value)在Lua中構建鍵/值表

mobz_buried = { 
{mob = "troll", quantity = 2} 
{mob = "warrior", quantity = 1} 
{mob = "wizard", quantity = 1}} -- sample data 

number_of_mobz_buried = 4 

xp_from_bury = 2000 -- another script generates these values, these are all just examples 

xp_per_corpse = xp_from_bury/number_of_mobz_buried 

for _, v in ipairs(mobz_buried) do 
    if type(mobz[v].kc) == "variable" then -- kc for 'kill count', number of times killed 
      mobz[v].kc = mobz[v].kc + 1 -- if it exists increment kc 
    else 
     mobz[v].kc = 1 -- if it doesn't exist create a key value that matches the mobs name and make the kc 1 
    end 
    if type(mobz[v].xp) == "variable" then -- xp for average experience points 
     mobz[v].xp = (((mobz[v].kc - 1) * mobz[v].xp + xp_per_corpse)/mobz[v].kc) -- just my formula to find the average xp over a range of differant buries 
    else 
      mobz[v].xp = xp_per_corpse -- if it doesn't exist create the table just like before 
    end 
end 

我試圖用mobz.troll = {kc, xp}, mobz.warrior = {kc, xp}, mobz.wizard = {kc, xp}並添加基於關閉名mobz_buried讓我的多個關鍵值的能力來結束。

+0

提供一個簡單的例子,表mobz_buried和mobz。 –

+1

請參見[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。你目前的例子不完整。 –

+0

你的'mobz_buried'表有一個值在'mobz'中沒有對應的元素,所以當你嘗試使用mobz [v]'然後索引到那個值時就沒有值,你會得到這個錯誤。請參閱https://eval.in/private/88f083da483307 –

回答

0

根據您評論的額外信息,聽起來好像您沒有爲​​構建表格。試試這個:

local mobz = {} 
for _, v in ipairs(mobz_buried) do 
    mobz[v.mob] = mobz[v.mob] or {} 
    mobz[v.mob].kc = (mobz[v.mob].kc or 0) + 1 

    -- etc... 
end 
+0

我試圖理解這一點。第3行說:'如果這個元素存在而不是保留它,如果不是將它創建爲空白元素?' –

+0

@EliBell我在任何地方都沒有在您的發佈代碼中看到該評論。這聽起來更像是,嘗試增加一個元素或如果它不存在創建並初始化爲一個。 – greatwolf

+0

感謝您的耐心,花了我一段時間才明白。但我現在看到在分配表值時使用'或'是我所缺少的 –