Returning nil value from a function

So, I made a function that generates a ban ID. Also, when it generate the id, it checks if the id already exists in the database, if it does, it generates a new one, otherwise it return the id. The issue is that when I call the function, and I print the returned value (so the ban id), it prints nothing.

This is what it prints (nothing)
image

The following, is the code

RegisterCommand('test-ban-id', function()
    print(BanId())
end)

function BanId()
    local base3 = math.random(1, 999)


    local base5 = math.random(1, 99999)

    local result = base3.. "-" ..base5

    MySQL.query('SELECT * FROM bannedplayers WHERE banid = ?', {result}, function(results)
        if #results > 0 then
            BanId()
        else
            return result
        end
    end)
end

Your mysql operation is asynchronous so your function will return before it done, and in your code you are only returning the result in the callback. You will have to either use a promise and await it or pass a callback in your BanId function and call that with the generated ban ID

Quick example

local p = promise.new()

MySQL.query("SELECT 1", {}, function(result)
    p:resolve(result)
end

local result = Citizen.Await(p)
print(result)
2 Likes

Right, that make sense now! Thank you so much for helping. Have a good day :grinning: