Loading other scripts in lua
Hello
Just wondering what the rules with "dofile" and "require" are, with regards to where it will look? In a simple example with two scripts (one needing code from the other) in the same folder as the Max patch, neither option seems to load in the script.
Many thanks
DiGiTaLFX
dofile and require haven't been modified for Max/Jitter. They are the stock Lua versions of the functions. The easiest way to load scripts relative to a currently loaded script is to use the path attribute of the jit.gl.lua object, which can be accessed in a script by:
print(this.path)
dofile(this.path.."/other.script.lua")
Adding search paths to require is a bit different. Require uses specially formatted strings stored in package.path and package.cpath for loading modules. You can add to the paths it searches by concatenating properly formatted strings to these variables. Here's a useful helper function:
function addmodulepath(path)
-- add to package paths (if not already present)
if not string.find(package.path, path, 0, true) then
package.path = string.format("%s/?.lua;%s", path, package.path)
package.path = string.format("%s/?/init.lua;%s", path, package.path)
package.cpath = string.format("%s/?.so;%s", path, package.cpath)
end
end
Use it as follows to load modules stored next to your script:
addmodulepath(this.path)
require("my.module")
Brilliant Wes, thanks for the explanation. Much appreciated!