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.

lua
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

lua
-- 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/3
Rellena los huecos

Completa el helper de depuración condicional para que solo imprima si está activado.

1-- config.lua → Config.Debug = true
2local function dbg(...)
3 if Config.Debug then ('[mi_recurso]', ...) end
4end
Pista

La función estrella para sacar valores por consola en Lua/FiveM.

Corrige el error

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:

1AddEventHandler('banco:dar', function(cantidad)
2 local src = source
3 local xPlayer = ESX.GetPlayerFromId(src)
4 xPlayer.addAccountMoney('bank', cantidad)
5end)

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

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:

How was this lesson?