簡體   English   中英

將數組傳遞給函數時出錯(Lua)

[英]Error with passing array to a function (Lua)

我收到此錯誤:嘗試索引字段“數組”(nil值),這是我的代碼:

aUItems = {}    
    aUItems[1] = tonumber(result[1].item_1)
    aUItems[2] = tonumber(result[1].item_2)
    aUItems[3] = tonumber(result[1].item_3)
    aUItems[4] = tonumber(result[1].item_4)
    aUItems[5] = tonumber(result[1].item_5)
    aUItems[6] = tonumber(result[1].item_6) -- Everything here is right, I checked it!
Network:Send(player, "UpdateAmount", aUItems ) -- Basicly calls the function

--function
function GK7Inv:UpdateAmount( array )
aItemsa[1] = array[1]
aItemsa[2] = array[2]
aItemsa[3] = array[3]
aItemsa[4] = array[4]
aItemsa[5] = array[5]
aItemsa[6] = array[6]
end

關鍵是您如何調用該函數,但我們尚未看到...

當您將函數定義為方法時 (使用:而不是. ),它具有一個名為self的隱式第一個參數。 調用它時,您必須傳遞self的值,這幾乎總是通過將其作為方法調用而隱式完成的。 如果您不這樣做,那么您的正式參數將不會與您的實際參數對齊。 Lua允許函數調用傳遞任意數量的參數,而不考慮形式參數的數量。 默認值為nil

因此,請確保調用這樣的方法:

GK7Inv:UpdateAmount(aUItems)
-- formal parameter self has the same value as GK7Inv
-- formal parameter array has the same value as aUItems

而不是這樣:

GK7Inv.UpdateAmount(aUItems)
-- formal parameter self has the same value as aUItems
-- formal parameter array has the default value nil

當然,您不必將函數定義為方法,在這種情況下,您將定義它並使用調用它.

function GK7Inv.UpdateAmount( array )
-- ...
end

或者,作為匿名函數,可能存儲在變量而不是表中

(function ( array ) -- don't store the function value, just it as an expression called as a function
-- ...
end)(aUItems)

function UpdateAmount( array ) -- store the function value in a global variable
-- ...
end
UpdateAmount(aUItems)

local function UpdateAmount( array ) -- store the function value in a local variable
-- ...
end
UpdateAmount(aUItems)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM