Global function?

Would this print “Ok there”?

Script 1:

function printhello()
   print("Ok there")
end

Script 2:

ScriptOne:printhello()

tl;dr I forgot how global functions work. I can’t figure out how to call them from another script.

2 Likes

To call a function from other script you must use a ModuleScript. You must script the functions into the ModuleScript, require the ModuleScript with require() and then call the function from a normal script.

2 Likes

So what will a global function do in the context of a script?

function A() end) -- basically useless since you cant call A() anywhere?

Has to be local function?

Global variables just don’t respect scope. A local variable will no longer exist once you exit the scope, whereas a global will. For example:

do
	local x = 1
	y = 2
end

print(x, y) --> nil, 2

The same holds true for functions, since they’re just another value that a variable can hold.

2 Likes
-- script 1
_G.sayhi = function(extra)
	print('hello',extra)
end
-- script 2
_G.sayhi('bootsareme')
-- 'hello bootsareme'

ModuleScripts as mentioned in the first reply are recommended, but this will do what you requested in your OP.

5 Likes

What’s the downside of using this, compared to modulescripts?

As far as I know, a global function may be conflictive if it uses a common name since you could accidentally call it in a script while defining another variable.

1 Like
  • Race conditions (if you declare a value stored in _G before it is defined in another script, it’ll obviously return nil)
  • No intellisense from script editor, even in Visual Studio (pretty trivial problem imo)

There’s probably other issues with it, but these are all the ones that I’ve come across so far.

If you do end up using _G, I’d recommend using it to store universal functions that you use across a lot of your scripts, such as for tweening, disconnecting script connections, etc., and declare them in a script in ReplicatedFirst to avoid any race conditions in runtime.