错误:尝试索引字段“?”(一个空值)

我在我的 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
点赞
用户1208078
用户1208078

这个错误通常来自于试图在不是表或 nil 的东西上索引字段。很可能在出现错误时 Account[i] 中的内容不是表或用户数据,而是内置类型,比如字符串或数字。

我建议你首先检查在出现错误时 Account[i] 中的内容类型,并从那里开始处理。

我知道的两种最常见的出现这个错误的方式如下:

local t = { [1] = {a = 1, b = 2}, [2] = {c = 3, d = 4} }
-- t[5] 是 nil,所以最终看起来像是 nil.a,是无效的
-- 这看起来不像是你的情况,因为你在 Account[i] 中检查了真实性
print(t[5].a)

你可能正在遇到以下情况:

local t =
{
    [1] = {a = 1, b = 2},
    [2] = 15, -- 呜呜!这里不应该有这个!
    [3] = {a = 3, b = 4},
}
-- 在这里,你期望 t 中的所有表都具有一致的格式。
-- 尝试在整数上引用字段 a 是没有意义的。
print(t[2].a)
2012-08-28 13:49:45