Sharing code#
Write a piece of code once and use it from every script in the world: the damage formula every weapon agrees on, the helper every door calls, the list of prices every shop reads.
The Modules object#
Make an object and name it Modules. Any script you put on it is a module: a script that hands something back with return.
local combat = {} -- How hard a hit lands at each level. Every weapon asks this one place.function combat.damage(level: number): number return 10 + level * 5end function combat.is_critical(roll: number): boolean return roll > 0.95end return combatAny script in the world, on any object, gets it with require:
local self = require("self")local combat = require("@modules/combat") self:on_touch(function(player) local hit = combat.damage(3) if combat.is_critical(math.random()) then hit *= 2 end print(player.name, "takes", hit)end)Change the formula in combat and save: every script that uses it restarts on its own with the new code. There is no second save to remember.
Modules on the same object#
A script can also require a script that sits on its own object, by its name. This is the way to split one big object script into parts:
local cards = require("./cards")./cards, cards and @modules/… all follow the same rules below.
How modules behave#
| Rule | What it means |
|---|---|
| A module runs inside the script that requires it | require("self") in a module is the object of the script that asked. A helper that moves "the object" moves the caller. |
| Each script gets its own copy | Two objects that require combat do not share its variables. To share data between objects, use events or the world store. |
| A module runs once per script | Requiring it twice, or spelling it two ways, gives back the same table. |
| Saving a module restarts its users | Their state starts over, as when you save them yourself. The creator console says which ones restarted. |
| A missing module is not the end | The script that required it gets an error now, and restarts when a module with that name is saved. |
| Two modules may not require each other | The error is cyclic require of module. Move the shared part into a third module. |
If two objects are named Modules, the older one (the lower id) is the one @modules/ reads. The name is matched without case, so modules works too.