【问题标题】:Error with passing array to a function (Lua)将数组传递给函数时出错(Lua)
【发布时间】:2013-12-21 08:13:36
【问题描述】:

我收到此错误:尝试索引字段“数组”(零值),这是我的代码:

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

【问题讨论】:

  • 您是否期望Network:SendaUIItems 传递给GK7Inv:UpdateAmount?好像不是这样的。
  • 是的。当我传递类似数字而不是 aUItems 的东西时(在这种情况下,我更改了函数)它工作正常。
  • @user3112337 你能贴出 Network:Send 的代码吗?
  • 也许你应该在调用函数UpdateAmount()时发布代码。
  • 所以如果你定义function GK7Inv:UpdateAmount( array ) print(type(array), array) end并且你做Network:Send(player, "UpdateAmount", 123)它会打印“数字123”而如果你定义Network:Send(player, "UpdateAmount", {})你它会打印“nil nil”?

标签: arrays lua


【解决方案1】:

关键是你如何调用函数,我们还没有看到......

当您将函数定义为方法时(通过使用: 而不是.),它有一个名为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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 2020-06-26
    相关资源
    最近更新 更多