10 min read
FiveM Resource Code Structure: Splitting a Script Into Files, Shared State and Escaping the 4000-Line client.lua
FiveM Resource Code Structure: Splitting a Script Into Files, Shared State and Escaping the 4000-Line client.lua
The owner asks you to drop the impound fee from $500 to $250. Ten seconds of work. You open the resource and there is one file in it. It is client.lua, it is four thousand lines long, the scroll bar is roughly the size of a Tic Tac, and Ctrl+F for 500 returns sixty-one hits, of which one is the impound fee, one is a millisecond delay, one is a max speed and the rest are anybody’s guess. At that point it has stopped being a script and become folklore. We call it client.lua but it is really more of a client.lore. FiveM resource structure is what everyone skips while shipping fast, and the invoice arrives about eighteen months later.
What follows: how the manifest decides load order and where globs betray you, what is safe to put in shared, how to write modules in a runtime with no require, keeping config out of logic so updates stop eating owners’ edits, splitting by feature instead of by layer, when a second resource earns the exports tax, and a recipe for taking a monolith apart without a weekend of downtime.
How fxmanifest.lua decides which files load, and in what order
The three script lists are not three folders, they are three execution contexts. On the client, every file in shared_scripts runs in the order listed, then every file in client_scripts. On the server, shared_scripts runs again from the top, then server_scripts.
shared_scripts {
'@ox_lib/init.lua',
'shared/init.lua',
'shared/config.lua',
'shared/util.lua',
}
client_scripts {
'client/main.lua',
'client/features/*.lua',
}
server_scripts {
'@oxmysql/lib/MySQL.lua',
'server/main.lua',
'server/features/*.lua',
}
The word “shared” trips people up constantly. It does not mean one copy both sides can see, it means the same text is executed twice, in two separate Lua states that never touch. Write a value into a shared table on the server and the client’s copy does not change. The @resource/path.lua form pulls a file out of another resource into your state, which is how ox_lib becomes a global you can call, and it runs at the position you list it, so put those first.
Then there are globs. client/features/*.lua matches every Lua file one level deep and **/*.lua recurses, but neither gives you a guaranteed order. In practice you get something close to alphabetical, so the day a colleague adds a_quickfix.lua, that file runs before every other feature file in the folder.
Whether that hurts depends on what the file does at the top level. Code inside CreateThread, an event handler or a function body is deferred and does not care what loaded first. Code at file scope cares a great deal: Garage.register(...) on line one of an alphabetically unlucky file is an index of a nil value, and the file dies there. So make it a rule. Globbed files define things and register handlers, they do not do things. Anything that must run at start-up goes in a file you list by name, at the bottom, where its dependencies already exist.
What belongs in shared_scripts, and what a client should never be handed
Every byte in shared_scripts and client_scripts is downloaded by every player who joins and left in their FiveM cache folder. Unless the resource is escrowed it is plain readable Lua on their disk, and escrow is a licensing wall rather than a security one.
| Safe in shared | Server-only, always |
|---|---|
| Coordinates, blip labels, item names, UI strings | Webhook URLs, API keys, database credentials |
| Prices and durations the client displays anyway | Admin and whitelist identifier lists |
| Pure helpers: formatting, distance maths, table utilities | Loot tables you would rather not see datamined |
| Locale and translation strings | Any value that decides whether an action is allowed |
One nuance, because it gets stated wrong constantly. Putting a price in shared config is not the vulnerability. The client reading your copy of a number is harmless. The vulnerability is the server trusting a number the client sent it. Shared config is read-only reference material on both sides, and the server always re-derives the authoritative value from its own copy before it pays anyone.
So keep two config files. shared/config.lua holds what a client legitimately needs. server/config.lua appears only in server_scripts and never reaches a player’s machine, so secrets live there or in a convar it reads at start-up. Whether your Lua ships readable at all is a separate business call, and the trade-offs are laid out well in this breakdown of FiveM escrow versus open source.
Writing Lua modules when your resource has no require
Each manifest file loads as its own chunk into one shared Lua state per context. That sentence explains the two things that confuse everyone. A local at the top of fileA.lua is invisible to fileB.lua, because it is an upvalue of that chunk only. And return MyModule at the bottom of a manifest-loaded file goes nowhere, because nothing captures the return value. It is not an error, it just quietly does nothing, which is worse.
To share anything you write a global. Globals are scoped to your resource, so your Garage table cannot collide with another resource’s Garage. The collision risk is inside your own four walls, where two files both decide to call something Utils and the second one silently wins. So claim exactly one global and hang everything off it, declared in the first file the manifest loads:
-- shared/init.lua
Impound = { config = {}, util = {}, state = {} }
-- client/features/release.lua
local Impound = Impound -- one global lookup, then a fast local
function Impound.releaseVehicle(plate)
...
end
That first line turns repeated global lookups into upvalue reads and documents what the file depends on. If you want real file-returning modules, ox_lib ships a loader, or you can build one with LoadResourceFile and load, remembering that an imported file must not also sit in the manifest and must appear in files {} to reach the client. Most resources never need it, and one namespace table is what the major frameworks do themselves.
Shared state follows the same discipline with one extra rule: it gets exactly one owner. One file writes Impound.state.onDuty, from one event handler, and everything else reads it. Three files writing the same flag is how you lose a Saturday. For state that other resources or the other side need, use state bags rather than exports. LocalPlayer.state, Player(source).state, Entity(vehicle).state and GlobalState replicate for you, and passing false as the third argument to :set keeps a value local when replication would be waste. Keep per-frame churn out of them, because every write is network traffic.
Keeping config separate so an update stops clobbering the owner’s edits
The classic ticket: an owner spends two hours tuning garages and prices, you release v1.4, they drag the new folder over the old one, and every edit is gone. They are annoyed and they are right to be. Good FiveM resource structure treats the config file as belonging to them, not to you.
Which means config.lua sits at the resource root, alone, containing data and nothing else. No CreateThread, no natives, no computed values. If a config file can throw an error, it is not a config file any more. Then never add a required key without a default, so an outdated config still boots. A defaults table with an __index metatable does that in three lines and costs nothing at runtime:
-- shared/defaults.lua (loaded AFTER config.lua)
local defaults = {
impoundFee = 500,
releaseTimeout = 30000,
notifyDuration = 5000,
}
setmetatable(Config, { __index = defaults })
Any key the owner has not set falls through to your default instead of returning nil at 3am. Keep locale strings in their own locales/ folder so a translation change and a price change are never the same file. And if you ship with escrow, every file the owner is meant to edit has to appear in escrow_ignore, because anything you forget gets encrypted and becomes a support queue you built for yourself. The packaging habits that separate a resource you use from a resource you sell are covered properly in this guide to becoming a FiveM creator.
Split by feature, not by layer, and name things so grep works
The instinctive split is by layer: client/events.lua, client/functions.lua, client/threads.lua, client/nui.lua. It looks like a filing cabinet, which is exactly why it feels right. Then you add one small feature and you are editing four files and reviewing four diffs to check you did not miss a fifth.
Work does not arrive layer-shaped, it arrives feature-shaped. So client/features/impound.lua holds the impound loop, the impound events and the impound NUI messages together, and deleting the feature is deleting one file. Layers still earn a place at genuine seams, like one file owning every database query. That is one file per seam, not one file per category.
Naming is the other half, and it pays out every time you go looking. Namespace every event with the resource name and the direction, because events are global across all resources on their side:
TriggerServerEvent('impound:server:releaseVehicle', plate)
RegisterNetEvent('impound:client:refreshList', function(vehicles) ... end)
Now grep -rn "impound:" resources/ gives you every producer and consumer in one screen, which an event called refreshList never will. Same logic for filenames: forty resources with a client/main.lua makes a cross-resource grep useless. Keep function names verb first with a consistent noun (releaseVehicle, impoundVehicle, listVehicles) instead of the doImpound and getVehList lucky dip, and never claim a one-word global like Core or Menu.
When it should be two resources instead of one
Split when the halves have genuinely different lifecycles, different owners, or when a third resource needs the thing on its own. Do not split because a folder is starting to look big. Big folders are free.
Be picky, because the boundary between resources is a real wall. Exports and events serialise their arguments, so tables are copied rather than passed, and functions and metatables do not survive the trip. A call that was a local function becomes meaningfully more expensive, which is invisible at ten calls a second and very visible inside a render loop. You also inherit a start-order problem, since an export on a resource that has not started yet throws, so you need dependencies in the manifest and a GetResourceState check for anything conditional. For the full picture of what crosses that wall, this walkthrough of FiveM exports, events and triggers is worth keeping open while you decide.
The refactor recipe: one function at a time, without breaking it
You do not need a rewrite. You need small moves and a restart between each one.
- Commit first, or copy the folder somewhere safe. Running
git initinside a resource takes four seconds and has saved more scripts than any linter. - Change the manifest before you move a single function. Rename
client.luatoclient/main.lua, update the path, restart, play the feature. If that alone breaks, you learned it cheaply. - Write down every
localdeclared at file scope in the monolith, then promote each one to the namespace table in place, before moving anything. A function closing overlocal activeJobworks fine today and silently reads a global nil the moment you move it elsewhere, because Lua does not error on reading an undefined global. It hands you nil and lets you find out at 2am. - Move pure functions first: formatting, maths, table helpers, anything with no upvalues and no natives. They go to
shared/util.luaand they cannot break. Then move leaves, meaning features nothing else calls into. - One function per move, then
restartand exercise it in game. It feels painfully slow and it is still faster than one 3000-line diff you cannot bisect. - Do not reformat while you restructure. A whitespace pass and a structural pass in one commit is a diff nobody can read, including you, next Tuesday.
One temporary tool helps with step three. Drop this at the top of your first-loaded file and watch the console for globals you did not mean to create:
setmetatable(_G, {
__newindex = function(t, k, v)
print(('^3[globals] wrote %s^7'):format(k))
rawset(t, k, v)
end
})
Expect noise from your framework, which writes plenty of globals into your state on purpose. You are hunting your own typos, so delete it before you ship or your console becomes a diary.
When a 200-line resource does not need any of this
FiveM resource structure is a cost, and below a certain size it never pays for itself. A 200-line script wants exactly three files: client.lua, server.lua, config.lua. Adding a features/ directory with one file in it does not make the code better, it makes you click through a folder tree to reach something that used to be on screen.
The honest signals that you have crossed the line: you scroll to find functions instead of reading to them, two people edited the file in the same week, a new feature has no obvious home, or you have copy-pasted the same helper three times. Somewhere north of 800 lines those tend to arrive together. Below that, leave it alone and go fix something that is actually broken.
So pick the worst file on your server, and do not refactor it. Just make the manifest change, move it into a folder, restart, confirm nothing caught fire. Then move one pure function out. Fifteen minutes, fully reversible, and the file goes from something nobody dares open to something with a door on it. Do that five times and client.lore turns back into client.lua, with a scroll bar you can actually grab.