Threads & timing
Loops, timers, promises and keeping things fast.
Developer Preview. Scripting is live on Neighborly servers – everything on these pages works today. The API is young, so tell us what you need next on Discord.
Lua in Neighborly is cooperative: your code runs until it finishes or waits. Threads let you run loops and delayed work without freezing the game or the server.
Creating threads
CreateThread(fn) starts a function as a thread (Citizen.CreateThread is the same function). Inside a thread, Wait(ms) pauses it and lets everything else run. Event handlers, command handlers, NUI callbacks and export calls already run as threads, so you can Wait in them too.
CreateThread(function()
while true do
local hour = GetGameTime()
if hour == 7 and not GlobalState.cafeOpen then
GlobalState.cafeOpen = true
elseif hour == 22 and GlobalState.cafeOpen then
GlobalState.cafeOpen = false
end
Wait(10000)
end
end)Timers
SetTimeout(ms, fn) runs a function once after a delay, without blocking the code that set it.
RegisterNetEvent('rtx_cafe:order', function(object)
local src = source
TriggerClientEvent('neighborly:notify', src, { text = 'Your order will be ready in a minute.' })
SetTimeout(60000, function()
if GetPlayerName(src) then
TriggerClientEvent('neighborly:notify', src, { text = 'Your order is ready!', type = 'success' })
end
end)
end)GetGameTimer() returns milliseconds since start and is the right tool for measuring durations and cooldowns. Note that the game clock (GetGameTime) is a different thing – it's the time in the neighborhood.
Promises and Citizen.Await
A promise is a value that arrives later. Create one with promise.new(), hand it out, and finish it with p:resolve(value) or p:reject(err). Citizen.Await(p) waits for it inside a thread and returns the value (or raises the error).
local pending = {}
local nextId = 0
local function askServer(name, ...)
nextId = nextId + 1
local p = promise.new()
pending[nextId] = p
TriggerServerEvent('rtx_lib:request', nextId, name, ...)
return Citizen.Await(p)
end
RegisterNetEvent('rtx_lib:response', function(id, result)
if pending[id] then
pending[id]:resolve(result)
pending[id] = nil
end
end)
CreateThread(function()
local balance = askServer('getBalance')
print('My balance is', balance)
end)local handlers = {
getBalance = function(src)
return GetBalance(src)
end
}
RegisterNetEvent('rtx_lib:request', function(id, name, ...)
local src = source
local handler = handlers[name]
if type(id) ~= 'number' or not handler then
return
end
TriggerClientEvent('rtx_lib:response', src, id, handler(src, ...))
end)This request/response pattern is what "server callbacks" are made of. You don't have to build it yourself: Neighborly has it built in as RegisterServerCallback and TriggerServerCallback, with timeouts and error handling – see Server callbacks. If you do roll your own, keep the list of handlers on the server explicit, as above – never let a client call any function by name.
Loops that react to where the player is
Client loops often check something about the player – are they near the counter, did they change lots. Natives that ask the game (like GetSimPosition) take a short round trip, so poll at a calm pace and only speed up while it matters. Wait(0) waits until the next tick.
CreateThread(function()
local shown = false
while true do
local sleep = 2000
local sim = GetActiveSim()
if sim and GetCurrentLot() == Config.CafeLot then
sleep = 500
local near = #(GetSimPosition(sim) - Config.Counter) < 2.5
if near ~= shown then
shown = near
if near then
exports.neighborly:showTextUI('Type /order to order a drink', { icon = 'coffee' })
else
exports.neighborly:hideTextUI()
end
end
end
Wait(sleep)
end
end)Performance tips
Client scripts run in the Neighborly launcher, not inside the game's frame, but every native call that asks the game still costs the game a little time. Keep idle loops at a second or more, and stop loops you don't need. Type resmon in the server console to see how many threads, events and exports each resource has.
- Prefer events over polling. Don't check
GetCurrentLot()in a loop – listen tolotEntered. Don't ask the server again and again – read a state bag and listen for changes. - Avoid endless
Wait(0)loops. Use the sleep pattern above so the loop only speeds up while the player is close. - Cache values that rarely change. Your own Sim, your household id and the current lot change rarely – store them in locals and update them from events.
- Batch network traffic. Send one event with a list instead of fifty events in a loop, and never trigger network events every frame.
- Do heavy work on the server, in steps. When processing many records,
Wait(0)every hundred items so the server keeps ticking smoothly for everyone. - Clean up. Remove objects, markers and handlers in
onResourceStop, and stop threads with a flag instead of leaving them running.