Loading other scripts in lua

    Apr 08 2012 | 11:01 am
    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

    • Apr 14 2012 | 5:03 pm
      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:
      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)
      Use it as follows to load modules stored next to your script:
    • Apr 15 2012 | 8:13 am
      Brilliant Wes, thanks for the explanation. Much appreciated!