luagrand-theft-autofivem

Nil Val fixed rhx


I am working on a script in FiveM and when the server starts I am getting "attempt to call a nil value (local 'cb')" in the console as an error. See code below that is talking about the nil value is cb(nil).

AddEventHandler("f:getPlayer", function(user, cb)
    if(Users)then
        if(Users[user])then
            cb(Users[user])
        else
            cb(nil)
        end
    else
        cb(nil)
    end
end)

So I found a post talking about adding "and cb" to the "if(Users)then" so the code looks like this.

AddEventHandler("f:getPlayer", function(user, cb)
    if(Users and cb)then
        if(Users[user])then
            cb(Users[user])
        else
            cb(nil)
        end
    else
        cb(nil)
    end
end)

But that did not fix the problem.

The results is to get the error to go away.


Solution

  • If cb is nil then you are still trying to use it like a function regardless of the check for cb being assigned a value. It should be:

    AddEventHandler("f:getPlayer", function(user, cb)
        if not cb then return end
        if(Users)then
            if(Users[user])then
                cb(Users[user])
            else
                cb(nil)
            end
        else
            cb(nil)
        end
    end)