Fundamentals: your first resource in QBCore · Lesson 2/5 · 10 min
Essential Lua for FiveM
Variables, tables, functions, conditionals and loops: just enough Lua to start writing scripts.
FiveM uses Lua, the same with ESX as with QBCore. You don't need to master the whole language: with variables, tables, functions and loops you can already do a lot. Let's get practical.
Variables and types
local nombre = 'Crxative' -- string
local vida = 100 -- number
local vivo = true -- boolean
local nada = nil -- absence of value
print(nombre, vida, vivo)Basic types
Always use local. Without local, the variable is global and may clash with other resources (causing bugs that are hard to find).
Tables (Lua's all-purpose tool)
-- List
local frutas = { 'manzana', 'pera', 'uva' }
print(frutas[1]) -- 'manzana' (indexes start at 1!)
-- Dictionary
local jugador = { nombre = 'Ana', dinero = 500 }
print(jugador.dinero) -- 500Tables
Functions
local function sumar(a, b)
return a + b
end
print(sumar(3, 4)) -- 7Functions
Conditionals and loops
local dinero = 500
if dinero >= 1000 then
print('rich')
elseif dinero > 0 then
print('getting by')
else
print('broke')
end
for i, fruta in ipairs(frutas) do
print(i, fruta)
end
for clave, valor in pairs(jugador) do
print(clave, valor)
endControl flow
Practice what you learned
0/3Esta variable está declarada como global por error y puede chocar con otros recursos. Conviértela en local.
Este código tiene un fallo:
nombre = 'Crxative'print(nombre)Reescríbelo corregido:
Pista
Sin local, la variable es global. Añade local delante de la declaración.
En Lua, ¿cuál es el primer índice de una lista (tabla secuencial)?
Completa el bucle que recorre una lista con su índice y su valor.
local frutas = { 'manzana', 'pera', 'uva' }for i, fruta in (frutas) do print(i, fruta)endPista
Para listas con índices numéricos en orden se usa ipairs; para diccionarios clave/valor, pairs.
Challenge: code it yourself
Write a Lua function that takes a table of numbers and returns their total sum.
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
Loop over the table with ipairs and accumulate into a variable that starts at 0.
Escribe aquí tu solución:
