Attempt to index a nil value (field '?') - Small example

Hello, I’m new to LUA, although I have a lot of scripting experience.

I am creating a basic loading script and assigning variables to learn.

I’m being given this error.

Attempt to index nil value.

PlayerInfo = {
    [0] = {
        PlayerName = "default",
        admin = 0,
        Job = 0,
    }
}

-- Event handler for when a player is connecting
AddEventHandler('playerJoining', function(oldIDs)
    local src = source

    if src == 1 then
        PlayerInfo[src].admin = 1
    end
    local admin = PlayerInfo[src].admin
    print('ADMIN LEVEL '..admin)
end)

Any assistance appreciated.

In Lua, arrays (or tables) are 1-indexed by default, which means that the first element (PlayerInfo in this case) is accessed with index 1, not 0. In your code, you have defined the PlayerInfo table with the first element having an index of 0

Change the PlayerInfo to:

PlayerInfo = {
    [1] = {
        PlayerName = "default",
        admin = 0,
        Job = 0,
    }
}

Similarly, when printing stuff (by default), lua has a hard time printing nils. To account for this, simply add an

or '0'

To keep the print function happy!

Your final string concat print should look like:

print('ADMIN LEVEL '.. admin or '0')

P.S. there’s a way to add additional logic, but I don’t remember it, nor do I think it’s necessary here;
Hope this helps!