Frameworks: ESX and QBCore · Lesson 2/5 · 10 min
ESX on the server: the player and their money
xPlayer is the player object on the server. With it you read and move their money safely.
On the server, everything revolves around xPlayer: the object that represents a connected player. You get it from the source (their server ID).
local xPlayer = ESX.GetPlayerFromId(source)
if not xPlayer then return end -- always check (may not be loaded yet)Get the player
Read and move money
-- Cash
local cash = xPlayer.getMoney()
xPlayer.addMoney(500) -- give 500€ in cash
xPlayer.removeMoney(200) -- take 200€
-- Accounts (bank, black_money…)
local bank = xPlayer.getAccount('bank').money
xPlayer.addAccountMoney('bank', 1000)
xPlayer.removeAccountMoney('bank', 1000)Money with ESX
ALL of this goes on the SERVER. Remember the client vs server lesson: money is moved where the authority is. Never give money from the client.
Example: paying for a validated action
RegisterNetEvent('pesca:server:vender')
AddEventHandler('pesca:server:vender', function(cantidad)
local src = source
local xPlayer = ESX.GetPlayerFromId(src)
if not xPlayer then return end
-- validate the amount on the server, don't trust the client
cantidad = math.min(tonumber(cantidad) or 0, 100)
if cantidad <= 0 then return end
xPlayer.addMoney(cantidad * 15) -- 15€ per fish
end)Payment validated on the server
Practice what you learned
0/3Obtén el jugador en el servidor a partir de su source y comprueba que existe.
local xPlayer = ESX.(source)if not xPlayer then return endPista
El jugador puede no estar cargado todavía; por eso siempre se comprueba después.
¿Cómo lees el dinero del banco de un jugador con ESX?
Falta comprobar que el jugador existe antes de tocar su dinero. Añade esa comprobación.
Este código tiene un fallo:
local xPlayer = ESX.GetPlayerFromId(source)xPlayer.addMoney(500)Reescríbelo corregido:
Pista
Si xPlayer es nil, xPlayer.addMoney peta el script. Añade el guard justo después de obtenerlo.
Challenge: code it yourself
Make a server event that charges 250€ from the player's bank and only proceeds if they have enough balance.
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
Read xPlayer.getAccount('bank').money and compare before removeAccountMoney.
Escribe aquí tu solución:
