错误:尝试索引字段 '?' (零值)

use*_*374 3 lua

我的 Lua 代码出现以下错误:

尝试索引字段 '?' (零值)

它发生在下面的粗体行上。我该如何解决?

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
Run Code Online (Sandbox Code Playgroud)

Mik*_*ran 7

此错误通常来自尝试在非表或 nil 的内容上索引字段。很可能无论Account[i]发生错误时处于什么位置,都不是表或用户数据,而是像字符串或数字这样的内置类型。

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)
Run Code Online (Sandbox Code Playgroud)

您可能遇到的情况很可能是这样的:

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)
Run Code Online (Sandbox Code Playgroud)