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

Hey everyone,

I’m trying to compare a number plate found in a SQL database to a vehicle in the open world. If I manage to get a positive match, everything is fine, however if I get a failed match (as the SQL result gives a nil result since it cannot find the number plate from in-game in the database), the script breaks and gives me the error:

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

How do I deal with receiving a nil result? Example code:

if carPlate == databasePlate then
– DO CODE
else
– DO SOME OTHER CODE
end

The script will do “SOME CODE” if the plates match but will kill the script in error rather than doing “DO SOME OTHER CODE”.

I apologize if this doesn’t make much sense as I’m quiet new to LUA programming but I thank you in advance for any help with this.

1 Like
if carPlate ~= nil--[[not nil]] and carPlate == databasePlate then
-- DO CODE
else
-- NIL OR "not databasePlate" CATCH
end

Sadly I still receive the same error.

Wait, you need to check if databasePlate ~= nil, right? that’s the nil one?

Yup - although I did try and switch around carPlate ~= nil and databasePlate ~= nil but it made no difference.

For anyone who can help, here is my code so far I started from scratch and tried doing a tidy up.

client\main.lua

> -- Send Client Number Plate to Server
> exports('clientPlate', function()
> 	local playerPed   = GetPlayerPed(-1)
> 	local coords 	  = GetEntityCoords(playerPed)
> 	local vehicle 	  = GetClosestVehicle(coords.x, coords.y, coords.z, 5.0, 0, 71)
> 	local getPlate 	  = GetVehicleNumberPlateText(vehicle)
> 
> 	TriggerServerEvent('Vehicles:Impound:clientPlateCheck', getPlate)
> end)

server\main.lua

> -- Recieve Number Plate from Client and Compare with MySQL Database Table
> RegisterServerEvent('Vehicles:Impound:clientPlateCheck')
> AddEventHandler('Vehicles:Impound:clientPlateCheck', function(plate)
> 	clientPlate = plate
> 	clientPlate = clientPlate:sub(1, -2)
> 	TriggerClientEvent('esx:showNotification', source, 'Server Receives Client Data: ' .. clientPlate)
>     local argString = table.concat(plate, " ")
> 	MySQL.Async.fetchAll('SELECT plate FROM h_impounded_vehicles WHERE plate = @plate', {
> 		['@plate'] = clientPlate
> 	}, 
> 	function(result)
> 		if result[1].plate == nil then
> 			TriggerClientEvent('esx:showNotification', source, '~r~Number plates dont match')
> 		else
> 			TriggerClientEvent('esx:showNotification', source, '~g~Number plates match')
> 		end
> 	end)
> end)

I now receive the following error instead
server.lua:34: bad argument #1 to 'concat' (table expected, got string)

You are trying to concat a string, that only works with tables

local argString = table.concat(plate, " ")

And it looks like your not even using that for anything, Heres something I wipped up that should do what you want it todo (with prints for debugging).

RegisterServerEvent('Vehicles:Impound:clientPlateCheck')
AddEventHandler('Vehicles:Impound:clientPlateCheck', function(plate)
    if plate == nil then print("Error plate is nil.") TriggerClientEvent('esx:showNotification', source, '~g~ Plate sent from client is nil.') return end

    MySQL.Async.fetchAll('SELECT plate FROM h_impounded_vehicles WHERE plate = @plate', {
            ['@plate'] = plate
        }, function(result)
        print("Dumping result table.")
        print(ESX.DumpTable(result))
        if result[1].plate == plate then
            print("Match found, Triggering client event back to source.")
            TriggerClientEvent('esx:showNotification', source, '~g~ Plate matches.')
        else
            print("Match not found, Triggering client event back to source.")
            TriggerClientEvent('esx:showNotification', source, '~r~ No match found.')
        end
    end)
end)
1 Like

If I directly copy and paste your code, I receive the error:
server.lua:38: attempt to index a nil value (global 'ESX')

So I commented out the following:
--print(ESX.DumpTable(result))

Then I get the following error:
SCRIPT ERROR: Execution of native 000000002f7a49e6 in script host failed: Argument at index 1 was null.

Now for some reason when getting the number plate from the closet vehicle, it adds an extra space at the end of the result (from previous testing). Example:
'JQP 043 '

So I added the following to remove the last character:
plate = plate:sub(1, -2)

But now I get the error:
SCRIPT ERROR: Execution of native 000000002f7a49e6 in script host failed: Argument at index 1 was null.

I didn’t think trying to compare a physical vehicle in front of the player ped and to a vehicle stored in the database table was going to be this difficult haha. I appreciate the help - hopefully this gets solved :slight_smile:

These are the results I get (facing known vehicle in database):

[script:hrp_pd_impoun] Dumping result table.
[script:hrp_pd_impoun] {
[script:hrp_pd_impoun] [1] = {
[script:hrp_pd_impoun]     ["plate"] = JQP 043,
[script:hrp_pd_impoun]     },
[script:hrp_pd_impoun] }
[script:hrp_pd_impoun] Match found, Triggering client event back to source.

These are the results if I face a vehicle that is known not to be in the database:

[script:hrp_pd_impoun] Dumping result table.
[script:hrp_pd_impoun] {
[script:hrp_pd_impoun] }
[script:hrp_pd_impoun] SCRIPT ERROR: @hrp_pd_impound/server.lua:43: attempt to index a nil value (field '?')
[script:hrp_pd_impoun] > <unknown> (@mysql-async/mysql-async.js:15543)
[  script:mysql-async]

Sorry for the multiple posts and edits. I am trying to solve this myself as best I can.

Current fullcode for the results above.

RegisterServerEvent('HRP:Impound:clientPlateCheck')
AddEventHandler('HRP:Impound:clientPlateCheck', function(plate)
    if plate == nil then 
		print("Error plate is nil.") 
		TriggerClientEvent('esx:showNotification', '~g~ Plate sent from client is nil.') 
		return 
	end
	
	plate = plate:sub(1, -2)

    MySQL.Async.fetchAll('SELECT plate FROM h_impounded_vehicles WHERE plate = @plate', {
            ['@plate'] = plate
        }, function(result)
        print("Dumping result table.")
        print(_ESX.DumpTable(result))
        if result[1].plate == plate then
            print("Match found, Triggering client event back to source.")
            TriggerClientEvent('esx:showNotification',  '~g~ Plate matches.')
        else
            print("Match not found, Triggering client event back to source.")
            TriggerClientEvent('esx:showNotification',  '~r~ No match found.')
        end
    end)
end)
1 Like

Hey what is on line 43? in the server.lua it seems to be a nil value

EDIT: You can also try this, I dont really know if this is the issue since i dont know whats on line 43 yet but feel free to drop this in instead

MySQL.Async.fetchAll('SELECT plate FROM h_impounded_vehicles WHERE plate = @plate', {
        ['@plate'] = plate
    }, function(result)
    print("Dumping result table.")
    print(_ESX.DumpTable(result))
    if result[1].plate then
        print("Match found, Triggering client event back to source.")
        TriggerClientEvent('esx:showNotification',  '~g~ Plate matches.')
    else
        print("Match not found, Triggering client event back to source.")
        TriggerClientEvent('esx:showNotification',  '~r~ No match found.')
    end
end)

The way this works is simple, It will check if there is a plate key in the table from msql and if there is it should be the same as the one passed over since you are fetching it with the desired license plate, I believe this is the issue as to why it drops a error when you dont get a plate stored in the database.

Line 43:
if result[1].plate == plate then

Every method I’ve tried works when retrieving the confirmed plate however I’d like to display an error message (using notifications) to the player when there is no match.

just remove the “== plate” part and should be good to go

Sadly it didn’t make any difference.

[script:hrp_pd_impoun] Dumping result table.
[script:hrp_pd_impoun] {
[script:hrp_pd_impoun] }
[script:hrp_pd_impoun] SCRIPT ERROR: @hrp_pd_impound/server.lua:43: attempt to index a nil value (field '?')
[script:hrp_pd_impoun] > <unknown> (@mysql-async/mysql-async.js:15543)
[  script:mysql-async]

I’ve spent over 15 hours (and I wish I was lying) using Google to try solve this issue whilst trying many methods but just can’t seem to find a way to deal with a nil result.

1 Like

Also, if I have any TriggerClientEvent’s in the function(result) block, I get the following error:

[    c-scripting-core] InvokeNative: execution failed: Argument at index 1 was null.
[script:hrp_pd_impoun] SCRIPT ERROR: Execution of native 000000002f7a49e6 in script host failed: Argument at index 1 was null.
[script:hrp_pd_impoun] > <unknown> (@mysql-async/mysql-async.js:15543)

UPDATE

And we’ve cracked it - I really appreciate your help throughout this. The debugging print was the biggest help, which for some odd reason I just never thought of doing. Here is the code used below for anyone who may come across this on Google.

RegisterServerEvent('HRP:Impound:clientPlateCheck')
AddEventHandler('HRP:Impound:clientPlateCheck', function(plate)
	_source = source;
    if plate == nil then
		print("ERROR: No plate received") 
		TriggerClientEvent('esx:showNotification', source, '~r~ERROR: ~s~You need to be facing a vehicle') 
		return
	else
		print('Plate Retrieved: ' .. plate)
	end
	
	plate = plate:sub(1, -2)

    MySQL.Async.fetchAll('SELECT plate FROM h_impounded_vehicles WHERE plate = @plate', {
            ['@plate'] = plate
        }, function(result)
        print("Table Result:")
        print(_ESX.DumpTable(result))
		if not next(result) then
			print('Fail: No Match & ' .. plate)
			TriggerClientEvent('esx:showNotification', _source, '~r~Failed') 
		else
			print('Success: ' .. result[1].plate .. ' & ' .. plate)
			TriggerClientEvent('esx:showNotification', _source, '~g~Success') 
		end
    end)
end)