Callbacks: ask a question, get an answer
Events are good when you just want to send a message and move on. But some situations need a reply. For example: "do I have enough money to buy this?" In that case the client asks a question, waits, and gets an answer back. That pattern is called a callback.
Build it
Make the resource folder
Inside your server's resources folder, create this folder:
resources/qu_callbacks
Create the files
Create this exact file layout:
resources/qu_callbacks/
fxmanifest.lua
server.lua
client.lua
Write fxmanifest.lua
Open fxmanifest.lua and paste this:
fx_version 'cerulean'
game 'gta5'
shared_script '@ox_lib/init.lua'
client_script 'client.lua'
server_script 'server.lua'
dependencies {
'ox_lib'
}
The dependencies { 'ox_lib' } block tells the server not to start qu_callbacks until ox_lib is running. The singular form dependency 'ox_lib' is tolerated, but the plural block is the canonical one, so use it. The shared_script '@ox_lib/init.lua' line is what actually loads the library and gives you the global lib on both the client and the server.
Write the lesson code
Open server.lua and paste this:
lib.callback.register('qu_callbacks:getBalance', function(src)
print('[qu_callbacks] server answering ' .. GetPlayerName(src))
return 500
end)
Open client.lua and paste this:
RegisterCommand('mybalance', function()
local balance = lib.callback.await('qu_callbacks:getBalance', false)
print('[qu_callbacks] my balance is ' .. balance)
end, false)
Start and test it
Make sure ox_lib starts first. Open server.cfg and add both lines in this order:
ensure ox_lib
ensure qu_callbacks
Save. Then, in the txAdmin Live Console (the same place you read server output - not the in-game chat and not your computer's terminal), type:
restart qu_callbacks
Join the server, then run this test from the chat box (press T) (this is a client command):
/mybalance
You will also see [qu_callbacks] server answering YourName in the txAdmin Live Console, proving the request crossed the network and the server is the one that produced the number.
Keep reading the full lesson
Sign in to start, then unlock every step of this lesson and the full FiveM School with a membership.
- How it works
- If something went wrong
- What you can do now
- Try it yourself
The remainder of Callbacks is available to FiveM School members.