3

I get the following error in my Lua code:

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

It happens on the line below in bold. How can I fix it?

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
3
  • 1
    It's hard to know why this error is happening without knowing where Account comes from and what it is expected to contain. Aug 28, 2012 at 10:29
  • A (meta)table, probably. It seems like a global variable here. Maybe you specified it as local incorrectly? Aug 28, 2012 at 10:35
  • 1
    please read this
    – Nir Alfasi
    Aug 28, 2012 at 16:35

1 Answer 1

8

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)
3
  • The message in your code is "attempt to index field '?' (a number value)" but the OP reports nil instead of number.
    – lhf
    Aug 28, 2012 at 17:55
  • good catch, i didn't even notice that... either way - it's hard to tell what exactly is wrong w/out a working example. Aug 28, 2012 at 18:01
  • I notice this error at times when I’ve copied code over from somewhere, and for some reason the spaces at the start of end of lines seem to become the issue. If I go through and ensure that any spaces (unless absolutely required) are removed it removes this error. (Not exactly sure of the cause maybe text formatting or something, but it’s a very hard to see unless you can tell spaces etc are present. Feb 15, 2022 at 10:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.