Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Can you call a function made on a different script and the actual function is on a different script?

Asked by 10 years ago

Can you call a function made on a different script and the actual function is on a different script?

2 answers

Log in to vote
2
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

The ModuleScript answer is a more elegant one. But there is an alternative.


A way to share values (including functions) is to use the global table _G.

_G is shared between all Script objects, or all Local Scripts on any single client (a LocalScript cannot use _G to talk to the server, or vice versa; local scripts running for different players cannot use _G to talk to each other).

--

_G is a little easier to set up, but much less elegant.

In this method, all scripts silently compete for names inside _G; the require solution makes it explicit where any particular value comes from.


In one script:

_G.func = function()
    -- whatever
end

-- (or)
function _G.func()
    -- Whatever
end

In another script (Both can be Scripts, or LocalScripts on the same client)

_G.func()

Note that unlike with require, we aren't guaranteed that the function will be defined by the time the second script runs, so if it is starting immediately, it should actually look like this:

repeat
wait();
until _G.func

_G.func()
Ad
Log in to vote
0
Answered by 10 years ago

You can do this using a module script which basically is a library in a way

Example:

Module script:

funct = function()
    print("Hello World!")
end

return funct --In a module script you must always return what you wish to grab in another script

Other script:

funct = require(Workspace.ModuleScript)

funct()

This would result in the output of Hello World!

0
funct(Swedish for thanks!This helps!)(That bracket was fake) Thanks!This helps! iluvmaths1123 198 — 10y

Answer this question