2012-08-28 40 views
2

我碰到下面的错误在我的Lua代码:错误:尝试索引字段'?' (一个零值)

attempt to index field '?' (a nil value)

它大胆发生在该线下方。我该如何解决它?

function SendMessageToAdmins(color1, color2, color3, msg) 
    for i = 0, maxSlots - 1 do 
     if Account[i] and Account[i].Admin >= 1 or Account[i] and Account[i].GameMaster >= 1 then 
      SendPlayerMessage(i, color1, color2, color3, string.format("%s", msg)) 
     end 
    end 
end
+1

很难要知道为什么会发生此错误,而不知道“Account”来自何处以及它期望包含哪些内容。 –

+0

可能是(元)表。这似乎是一个全局变量。也许你把它指定为本地不正确? –

+1

请阅读[*此*](http://stackoverflow.com/questions/how-to-ask) – alfasin

回答

4

这个错误通常来自于尝试索引某个不是表格的字段或零。机会是,无论是在Account[i]错误发生时,不是一个表或userdata,而是一个内置类型,如字符串或数字。

我会与检查无论是在Account[i]当你得到的是错误的类型,并从那里开始。

两种最常见的方式看到这个错误(据我所知)低于:

local t = { [1] = {a = 1, b = 2}, [2] = {c = 3, d = 4} } 
-- t[5] is nil, so this ends up looking like nil.a which is invalid 
-- this doesn't look like your case, since you check for 
-- truthiness in Account[i] 
print(t[5].a) 

你可能遇到的情况,很有可能是这一个:

local t = 
{ 
    [1] = {a = 1, b = 2}, 
    [2] = 15, -- oops! this shouldn't be here! 
    [3] = {a = 3, b = 4}, 
} 
-- here you expect all the tables in t to be in a consistent format. 
-- trying to reference field a on an int doesn't make sense. 
print(t[2].a) 
+0

在你的代码的消息是“企图索引字段‘?’ (数字值)“,但OP报告* nil *而不是* number *。 – lhf

+0

好抓,我甚至没有注意到......无论哪种方式 - 很难说出一个工作示例究竟出了什么问题。 –

相关问题