About This File
Based on this thread, I decided to write a version of require() for mods. The use() function works just like require(), but looks for files taking the (root) mod directory as a base and runs them inside the mod environment.
Feel free to just drop use.lua into your mods. Below is some documentation on its behaviour, and I attached a simple sample mod ("usage") to show how to use it in practice.
To enable use(), place use.lua in your mod directory and callmodimport "use.lua"
from modmain.lua, modworldgenmain.lua or both.
Acts like require(name), but looks for name relatively to the mod directory and runs it in the mod environment. The usual rules for result caching and return values apply, i.e. calling use() on the same file more than once will not run it again, just evaluate to its return value (if any, and to true otherwise). As in require(), the extension ".lua" should not be included, and path components can be freely separated by any of "/", "" or ".". Note that, again as in require(), the caching is based on the literal name given, so while "some/thing" and "some.thing" may evaluate to the same file, calling both will cause the file "some/file.lua" inside your mod folder to be run twice.
Exports use as a (virtual) package called id, so that it becomes accessible from outside the mod environment. So, for instance, by calling use:ExportAs("mymod.use") you may fetch it from within, say, a prefab file, by callinglocal use = require "mymod.use"
The id should be a unique name to avoid clashes with the game and other mods, so using your mod's name as part of it is recommended.
Sets the environment to run the loaded files in. If unset, the mod environment is used. It can be fetched by calling use:GetEnvironment().
Returns the mod environment, regardless of whether something has been passed to use:SetEnvironment(). Its purpose is to allow mod variables to be accessed from outside the mod environment by coupling its use with use:ExportAs().
Returns the modinfo (i.e., a table with the modinfo entries). It is equivalent touse:GetModEnvironment().modinfo
Why "use" and not "modrequire"?
While modrequire would be the most logical name for it, my wicker framework already defines a function called modrequire, which serves a similar but different purpose. So, to avoid name clashes, a picked "use".