3

我的 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
4

1 回答 1

7

this error usually comes from trying to index a field on something that isn't a table, or nil. chances are that whatever is at Account[i] when the error happens, isn't a table or userdata, but a built in type like a string or number.

i'd start with checking the type of whatever is in Account[i] when you get that error, and going from there.

the two most common ways to see this error (that i know of) are below:

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)

the case you are probably experiencing, is most likely this one:

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)
于 2012-08-28T13:49:45.047 回答