Debug errors like a pro · Lesson 2/3 · 8 min
print: your best friend for debugging
When you don't know why something fails, make the code tell you what's happening.
80% of debugging is knowing what value a variable holds at a certain point. That's what print is for: you place messages that tell you where the code goes and with what data.
RegisterNetEvent('banco:retirar')
AddEventHandler('banco:retirar', function(cantidad)
local src = source
print('[banco] withdraw requested by', src, 'amount:', cantidad)
local xPlayer = ESX.GetPlayerFromId(src)
print('[banco] does xPlayer exist?', xPlayer ~= nil)
if not xPlayer then return end
print('[banco] current balance:', xPlayer.getAccount('bank').money)
end)Strategic prints
A debug switch
-- config.lua
Config.Debug = true
-- helper function
local function dbg(...)
if Config.Debug then print('[mi_recurso]', ...) end
end
dbg('this only shows if Config.Debug = true')Conditional debug
Put prints BEFORE and AFTER the suspicious point. If the first one shows and the second doesn't, the failure is in between. When you're done, set Config.Debug to false (don't leave spam in production).
Practice what you learned
0/3Completa el helper de depuración condicional para que solo imprima si está activado.
-- config.lua → Config.Debug = truelocal function dbg(...) if Config.Debug then ('[mi_recurso]', ...) endendPista
La función estrella para sacar valores por consola en Lua/FiveM.
Este evento da dinero pero 'no funciona' y no lanza error. Añade un print para ver qué llega.
Este código tiene un fallo:
AddEventHandler('banco:dar', function(cantidad) local src = source local xPlayer = ESX.GetPlayerFromId(src) xPlayer.addAccountMoney('bank', cantidad)end)Reescríbelo corregido:
Pista
Un print al entrar con 'cantidad' (y si xPlayer existe) te dice si el handler corre y con qué datos.
Ordena el código para que los prints 'rodeen' la operación sospechosa (antes y después).
Coloca las líneas en el orden correcto con las flechas.
print('[banco] nuevo saldo:', xPlayer.getAccount('bank').money)xPlayer.addAccountMoney('bank', cantidad)print('[banco] antes de dar, cantidad:', cantidad)Pista
Print ANTES del punto sospechoso, ejecutas la acción, y print DESPUÉS para ver el resultado.
Challenge: code it yourself
A function doesn't give money and you don't know why. Add prints to see if it's entered, if the player exists and what amount arrives.
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
A print on entry, one after GetPlayerFromId (xPlayer~=nil) and one with the amount.
Escribe aquí tu solución:
