Trying to return a Server value to the Client

I’m trying, through the Server, to return a value through AddEventHandler to the Client, and I want to store this returned value in a variable

First, I defined the function on the server side:

RegisterNetEvent('verificar')
AddEventHandler('verificar', function()
    print("SERVER")
    if 5 == 4 then
        print("true")
        return true
    else
        print("false")
        return false
    end
end)

Then I tried to store the returned value in a client-side variable:

local verify = TriggerServerEvent("verificar")
    print("CLIENT")
    print(verify)

However the value in which the function returns to the client is a completely a random number:

screenshot.374

How do I pass a value from Server to Client?

On the server you want RegisterServerEvent, so it would look like:

RegisterServerEvent("verificar")
AddEventHandler("verificar", function()

That’s not how that works I’m afraid.

To return that value from the server back to the client, you need to use TriggerClientEvent, so what you want would look like this:

-- client.lua
TriggerServerEvent("verificar")

RegisterNetEvent("verificar:Return")
AddEventHandler("verificar:Return", function(verify)
    print("CLIENT", verify)
end)

-- server.lua
RegisterServerEvent('verificar')
AddEventHandler('verificar', function()
    print("SERVER")
    if 5 == 4 then
        print("true")
        TriggerClientEvent("verificar:Return", source, true)
    else
        print("false")
        TriggerClientEvent("verificar:Return", source, false)
    end
end)

source is the Server ID of the player that triggered the event, you can read more about that here. The :Return is just a naming convention I use, it can be whatever you want.

Hope that clears it up for you.

2 Likes

IIRC RegisterNetEvent and RegisterSeverEvent do the same thing. RegisterServerEvent is deprecated.

2 Likes

Learning some new every day, I had no idea lol, thank you.

1 Like