You can insert methods into the global _G table like you would any other table.
In case you did not know _G was a reference to a table, or didn't know how to add methods(functions) to a table, see below code for an example.
function _G.Print(str)
print("SERVER: "..str)
end
That creates a custom print method called Print, and can be used in other scripts like so:
wait(1)
_G.Print("Hello")
The reason I added a wait to the top of the script, is because it is not guaranteed that the other script will have added it by the time this script tries to index it. Not having a wait may result in an error.
Note, I used standard function notation, you can also define it using a variable format:
_G.Print = function(str)
print("SERVER: "..str)
end
It can be considered poor practice to fill the _G table with tons of methods, rather it is widely accepted to use ModuleScripts instead. (As has been pointed out by other members)
ModuleScripts run once they are required, and they must return exactly one value. This is commonly a table, but can be anything such as a function.
What I would recommend doing, since you already are attempting to use a table and load it with methods, is do just that, but in a ModuleScript. How this would work, is inside the module you would create a table, and then insert the methods similar to how I showed above.
Then you would return the table.
Inside any of your scripts, you would require the module and store it in a variable in each of the scripts you want to use it for. After that point, the usage is the same.
ModuleScript:
local library = {}
function library.Print(str)
print("SERVER: "..str)
end
return library
Script:
local library = require(script.ModuleScript)
library.Print("Hello")
A wait is not needed for modules, because requiring them ensures they are loaded.
2 comments
You would use module scripts instead since module scripts > _G.
^ Correct.