Frameworks: ESX and QBCore · Lesson 3/5 · 9 min
ESX callbacks: requesting data from the server
When the client needs an answer from the server (do I have balance? what items do I have?), you use a callback.
A normal event is one-way (the client notifies the server). But sometimes the client needs a RESPONSE: «do I have enough money for this?». That's what server callbacks are for.
On the server: register the callback
ESX.RegisterServerCallback('tienda:comprar', function(source, cb, precio)
local xPlayer = ESX.GetPlayerFromId(source)
if not xPlayer then return cb(false) end
if xPlayer.getMoney() >= precio then
xPlayer.removeMoney(precio)
cb(true) -- respond to the client: purchase OK
else
cb(false) -- no money
end
end)server.lua
On the client: call it and wait for the response
ESX.TriggerServerCallback('tienda:comprar', function(exito)
if exito then
print('Purchase completed')
else
print('Not enough money')
end
end, 1500) -- 1500 = price passed to the serverclient.lua
The decision (does the player have money?) and the charge happen on the SERVER. The client only receives yes/no. That way cheating is impossible.
Practice what you learned
0/3Ordena un callback de servidor que cobra un precio solo si el jugador tiene dinero.
Coloca las líneas en el orden correcto con las flechas.
local xPlayer = ESX.GetPlayerFromId(source)end) if xPlayer.getMoney() >= precio then xPlayer.removeMoney(precio) cb(true) else cb(false) endESX.RegisterServerCallback('tienda:comprar', function(source, cb, precio) if not xPlayer then return cb(false) endPista
Primero registras el callback, luego obtienes el jugador, validas y respondes con cb().
Completa la llamada del cliente que pide al servidor y espera la respuesta.
ESX.('tienda:comprar', function(exito) if exito then print('Compra OK') endend, 1500)Pista
Es la pareja cliente de RegisterServerCallback; el 1500 es el precio que se pasa al servidor.
En un callback de ESX, ¿dónde se decide si el jugador tiene dinero y se le cobra?
Challenge: code it yourself
Create a callback that returns true only if the player has the 'police' job.
Write it yourself in your editor (VS Code) and test it on your server. You learn here by doing it, not by copying.
See hint
Compare xPlayer.job.name == 'police' and respond with cb(true/false).
Escribe aquí tu solución:
