0
votes

I'm working on a phone script for Fivem when a player joins the counsel gets this error. "SCRIPT ERROR: @phone/server/server.lua:64: attempt to index a nil value (local 'result')

handler (@phone/server/server.lua:581)"

I am going complete blank on a way to fix this error. Any would-be greatly appreciated.

code from line 64

function getNumberPhone(identifier)
  local result = MySQL.Sync.fetchAll("SELECT users.phone_number FROM users WHERE users.identifier = @identifier", {
      ['@identifier'] = identifier
  })
  if result[1] ~= nil then
      return result[1].phone_number
  end
  return nil

code from line 581

AddEventHandler('Phone:allUpdate', function()
    local sourcePlayer = tonumber(source)
    local identifier = getPlayerID(source)
    local num = getNumberPhone(identifier)
    TriggerClientEvent("Phone:myPhoneNumber", sourcePlayer, num)
    TriggerClientEvent("Phone:contactList", sourcePlayer, getContacts(identifier))
    TriggerClientEvent("Phone:allMessage", sourcePlayer, getMessages(identifier))
    TriggerClientEvent('Phone:getBourse', sourcePlayer, getBourse())
    sendHistoriqueCall(sourcePlayer, num)
end) 
1
I can't tell very well from what you've given me, but it looks like a function call in AddEventHandler (probably getNumberPhone?) triggers a function which leads you to line 64. Whatever is in that function, result is definitely nil. I know this because your error says "attempt to index a nil value (local 'result')"joehinkle11
Add there entire code block leading to line 64 and I might be able to helpjoehinkle11
updated it. thought I had the whole block my bad.Nix
it looks like the error should be occurring at "if result[1]" not "return result[1].phone_number". Is this correct?joehinkle11
That is right..Nix

1 Answers

1
votes

By adding result ~= nil and to your if statement the error should go away.

function getNumberPhone(identifier)
  local result = MySQL.Sync.fetchAll("SELECT users.phone_number FROM users WHERE users.identifier = @identifier", {
      ['@identifier'] = identifier
  })
  if result ~= nil and result[1] ~= nil then
      return result[1].phone_number
  end
  return nil

The problem is that sometimes your SQL query is returning nil, which sets result to nil. Then you try to access 1 on result, which is nil, so it throws the error "attempt to index a nil value".

To fix this, just make sure that result isn't nil before attempting to lookup a key on it.