Example for require() to be able to access a script's functions from another script

Major thanks to Discord user FleshyOverlord for originally making this.

SNIPPET TITLE: Lua Require() example by @FleshyOverlord
SKILL LEVEL: Easy

WHAT DOES IT DO?:
Require() essentially lets you embed a script into other scripts. This means you can access the script's functions in either script.

EXAMPLE USE CASES:
This is useful for when you want to have a script that you use in multiple places, but only want to update once when making changes. For instance, you can have a script that generates projectiles based on a bunch of properties, and then drop that script into multiple weapons. Each weapon call call the original script's functions, and you only have to change it once to update them.

BASE SNIPPET
GreetingsModule.lua

--Create an object that can be grabbed using "require"
local API = {}
--A simple function that prints "Hello World"
function API.PrintGreetings()
  print("Hello World")
end
--Return the "API" object so that it can be required
return API

RequireTest.lua

--Asset Reference to the "GreetingsModule.lua" file
local requiredScript = script:GetCustomProperty("GreetingsAPI")
--Pull the API module from the "GreetingsModule.lua" script
local GreetingsAPI = require(requiredScript)
--Call the "PrintGreetings" funnction from the "API" module 
GreetingsAPI.PrintGreetings()
2 Likes

I learned about this from the script

BasicGameStateManagerServer

the script has a custom propertie of type

Asset Reference

that points to the script

APIBasicGameState

and the script itself has this line of code
local ABGS = require(script:GetCustomProperty("API"))

however for my own scripts since i can only create scripts in the hierarchy view with makes them of type

Core Object Reference

i need to right click my script and choose

Create New Template From This

to turn my script into a template and then i can pass it to a custom property of type Asset Reference.

Edit: seams like turning scripts into templates did not work event log complains about

require() asked to load asset which is not a script

but now i was able to drag and drop the script from the project content tab, could not do that before don't know why.

1 Like