Created
February 12, 2024 20:34
-
-
Save DemmyDemon/7ba094e632c069d81d50106bfb2fe2bb to your computer and use it in GitHub Desktop.
Server Calls shared_script for FiveM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if IsDuplicityVersion() then | |
local calls = {} | |
---Define a server-side call that a client can use to run code on the server. | |
---@param name string The uniquely identifying name of this call. | |
---@param code function The function to run when this call is made | |
---@return table eventData The event data associated with the event that was registered to handle this call. | |
function DefineServerCall(name, code) | |
local finalName = string.format("%s:RPC:%s", GetCurrentResourceName(), name) | |
if calls[finalName] then | |
RemoveEventHandler(calls[finalName]) | |
end | |
RegisterNetEvent(finalName) | |
calls[finalName] = AddEventHandler(finalName, function(reference, ...) | |
local source = source | |
local success, data = pcall(code, ...) | |
TriggerClientEvent(finalName, source, reference, success, data) | |
end) | |
return calls[finalName] | |
end | |
else | |
local timeout = 5000 | |
---Call a function previously registered on the server, that will run and return here. | |
---@param name string The uniquely identifying name of this call. | |
---@param ... any The arguments to be passed to the function when it runs on the server | |
---@return boolean success Did the call succeed, or was there some kind of error? | |
---@return table|string result Whatever was returned from the function run server-side, or the error generated in the attempt. "CALL TIMEOUT" indicates that the server did not respond on time. | |
function ServerCall(name, ...) | |
local finalName = string.format("%s:RPC:%s", GetCurrentResourceName(), name) | |
local started = GetGameTimer() | |
local reference = started + GetFrameTime() | |
local success, data | |
RegisterNetEvent(finalName) | |
local handle = AddEventHandler(finalName, function(returnRef, callSuccess, returnData) | |
if returnRef == reference then | |
success = callSuccess | |
data = returnData | |
end | |
end) | |
TriggerServerEvent(finalName, reference, ...) | |
while success == nil do | |
Citizen.Wait(0) | |
if GetGameTimer() > started + timeout then | |
RemoveEventHandler(handle) | |
return false, 'CALL TIMEOUT' | |
end | |
end | |
RemoveEventHandler(handle) | |
return success, data | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment