Global function?

Would this print “Ok there”?

Script 1:

function printhello()
   print("Ok there")

Script 2:


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


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.


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:

	local x = 1
	y = 2

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

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

-- script 1
_G.sayhi = function(extra)
-- script 2
-- 'hello bootsareme'

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


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.