Fundamentals: your first resource · Lesson 2/6 · 10 min

Essential Lua for FiveM

Variables, tables, functions, conditionals and loops: just enough Lua to start writing scripts.

FiveM uses Lua. You don't need to master the entire 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 can clash with other resources (causing hard-to-find bugs).

Tables (Lua's all-rounder)

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

-- Iterate over a list
for i, fruta in ipairs(frutas) do
  print(i, fruta)
end

-- Iterate over a dictionary
for clave, valor in pairs(jugador) do
  print(clave, valor)
end

Control flow

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

Iterate over the table with ipairs and accumulate into a variable that starts at 0.

Escribe aquí tu solución:

How was this lesson?