Loading other scripts in lua

Apr 8, 2012 at 11:01am

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

#62823
Apr 14, 2012 at 5:03pm

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")
#226781
Apr 15, 2012 at 8:13am

Brilliant Wes, thanks for the explanation. Much appreciated!

#226782

You must be logged in to reply to this topic.