Jump to content

call resource exported function easily.


Vector

Recommended Posts

hello, I want to show you an easier way of calling functions exported by other resources, adding a few lines of code in your script file.

suppose you have a resource called "myResource". And this resource exports a function "foo" wich you want to call by other resource.

the proper way to do that, according with https://wiki.multitheftauto.com/wiki/Call is ...

  
exports.myResource:foo (...); 
-- or ...  
call (getResourceFromName("myResource"), "foo", ...);  
  

if you add the lua code below, you´ll be able to call foo like this->

  
importFunctions ("myResource"); -- import the functions exported by "myResource" 
foo (...);  -- easy way. 
  

you need to add the next script lines in your file. ->

  
function importFunctions (resourceName)  
    local resource = getResourceFromName (resourceName); 
    if not resource then 
        outputDebugString ("Couldnt import functions from \"" .. resourceName .. "\" resource because" .. "it doesnt exist!", 2); 
        return; 
    end; 
    local exportedFuncNames = getResourceExportedFunctions (resource); 
    if not exportedFuncNames then return end; 
    for i,j in ipairs (exportedFuncNames) do 
        _G [j] = function (...) call (resource, j, unpack ({...})); end; 
    end; 
end; 
  

also, you can import functions for different resources. in fact, if two resources have a function with the same name, one function will replace the other one.

here is an example ->

  
-- 1º st resource "myResource_1" have two functions: foo, bar. 
-- 2º nd resource "myResource_2" have the next exported funcs: bar, foobar.  
  
importFunctions ("myResource_1"); -- import funcs.  
foo (...);   -- calling to exports.myResource_1.foo 
bar (...);   -- calling to exports.myResource_1.bar 
  
importFunctions ("myResource_2"); 
foo (...);   -- calling to exports.myResource_1.foo 
bar (...);   -- now calling to exports.myResource_2.bar 
foobar (...);  -- calling to exports.myResource_2.foobar 
  

hope you find this useful.

Edited by Guest
Link to comment
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...