Blog
How to Write a FiveM Script: Your First Script in Lua
Published:
1. The resource folder and fxmanifest.lua
Each script is its own folder inside the server's resources folder; FiveM calls these resources. The fxmanifest.lua file in the folder describes the script: fx_version, game 'gta5' and which files run on the client and which on the server. To add it to the server, an ensure line goes into server.cfg.
2. Client and server
Code in the client folder runs on the player's computer: drawing on screen, keys, the player's character. Code in the server folder runs on the server: money, items, the database. Important decisions are always made on the server.
3. Events
The client and server talk through events. The client sends a request to the server with TriggerServerEvent, the server listens for it with RegisterNetEvent, and the server sends messages to the client with TriggerClientEvent.
4. Working with ESX, QBCore and Qbox
Money, jobs and the inventory are handled through the framework's own functions, and their names differ in each framework. To support several frameworks, those calls are gathered in a single bridge file; that is how Gunrack runs on ESX, QBCore and Qbox.
5. Performance: resmon
The most common mistake is a loop that runs every frame (60 times a second or more): it keeps the CPU busy even when the player is far away and slows the game down. The loop should check rarely while the player is not close. Instead of a per-frame loop, Gunrack runs a light check every 300 milliseconds; its resmon value in game is 0.00 ms on foot.
-- Measures the distance 60+ times a
-- second even when the player is far away
CreateThread(function()
while true do
Wait(0)
local pos = GetEntityCoords(PlayerPedId())
if #(pos - Config.Point) < 2.0 then
DrawPointMarker()
end
end
end)-- Simplified example
CreateThread(function()
while true do
local sleep = 500
local pos = GetEntityCoords(PlayerPedId())
if #(pos - Config.Point) < 10.0 then
-- Draws every frame only when close
sleep = 0
DrawPointMarker()
end
Wait(sleep)
end
end)6. Security: do not trust the client
Code on the player's computer can be tampered with. Every action that gives items or adds money must be checked again on the server: the player's job, distance and what is really in the inventory. We showed example code for this in our post "Getting a FiveM Script Made".
7. If you will sell it: escrow
If you will sell the script, you can protect it with Cfx.re's escrow: the config files stay open and the core code is locked. That is how we sell our own scripts through Tebex.
If you would rather not do it yourself
We write FiveM scripts made for your server; a custom script starts from $30 and is usually delivered in 3-7 days.
Product
GunrackVehicle gun rack for FiveM. Officers store weapons and ammo inside department vehicles.
Related service
Custom FiveM Script Development