Calling a function from a different resource

What’s the best way to go about this, let’s say trigger function xyz in resource1, from resource 2?

Let’s say that function is to show a badge, and I wanna add it to esx_policejob F6 menu, would I add
export ‘xyz’ to _resource.lua of the resource1 and exports.resource1:xyz() to resource2?

Is there a better or a different way to get this done since I’m unable to get it to work :smiley:

Thanks!

Imagine that you have the following function:

function test(x)
    --code
end

There are two ways to export your function

the first is export it automatically inside the script:

exports('test', function(x)
  --code
end) -- this will cause the function to be declared and exported automatically

or you can create the function normally, and insert the following line in your fxmanifest.lua

if the function is on the client-side:

client_scripts 'client.lua'
export 'test' -- exports the "test" function from the client-side script above

if the function is on the server-side:

server_script 'server.lua'
server_export 'test' -- exports the "test" function from the server-side script above

Now to use the exported function in other resources it is quite simple, you will need to use the “exports” class and indicate the name of the resource and the function as follows: exports.ResourceName:function(parameters)

let’s imagine that the name of the resource in which the function “test” was exported is called “resourceTest”:

exports.resourceTest:test(3) -- will call the test function of the resource resourceTest and with parameter 3

Now you can use the “test” function on any resource and any script :smiley:

for your curiosity, Lua offers a “dofile” function that executes another script next to the current script, but it is not recommended to be used in FiveM

dofile("./script.lua")
1 Like

Hey @Vinni_Marcon

Thanks for the detailed explanation, although I feel like I’ve made progress, I’m still running into an issue. Either nothing happens, or I get an error in the console similar to this one.

 @esx_ambulancejob/client/job.lua:109: attempt to index a nil value (global 'DetailedHealth')

This problem occurs when a variable should be receiving a value from somewhere, but it is not. In this case, you are probably calling an external function that needs some other internal function to pass a value to it. You need to find out what passes a value to variable DetailedHealth and, if so, why isn’t it passing