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

lua
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)

lua
-- List
local frutas = { 'manzana', 'pera', 'uva' }
print(frutas[1]) -- 'manzana' (indexes start at 1!)

-- Dictionary
local jugador = { nombre = 'Ana', dinero = 500 }
print(jugador.dinero) -- 500

Tables

Functions

lua
local function sumar(a, b)
  return a + b
end

print(sumar(3, 4)) -- 7

Functions

Conditionals and loops

lua
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)
end

Control flow

Practice what you learned

0/3
Corrige el error

Esta variable está declarada como global por error y puede chocar con otros recursos. Conviértela en local.

Este código tiene un fallo:

1nombre = 'Crxative'
2print(nombre)

Reescríbelo corregido:

Pista

Sin local, la variable es global. Añade local delante de la declaración.

Test

En Lua, ¿cuál es el primer índice de una lista (tabla secuencial)?

Rellena los huecos

Completa el bucle que recorre una lista con su índice y su valor.

1local frutas = { 'manzana', 'pera', 'uva' }
2for i, fruta in (frutas) do
3 print(i, fruta)
4end
Pista

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:

How was this lesson?