## require() a file next to LUA file

danell
Posts: 36
Joined: Mon Dec 12, 2016 6:32 am
Been thanked: 1 time

### require() a file next to LUA file

I'm working on a script that's starting to become pretty big and I want to split it up in mutliple files to have some control.
I'm trying to to use require() to get the data from the other lua files next to my main file but I only get an error that Fusion can't find that file.
The problem is that Fusion is looking inside the Modules\Lua folder and not right next to my main file as it should do (when looking on lua-information out there).
Are there any way to make Fusion look for the file right next to my main LUA file or am I doomed and have to move my extra files to Modules\Lua?

SirEdric
Fusionator
Posts: 1820
Joined: Tue Aug 05, 2014 10:04 am
Real name: Eric Westphal
Been thanked: 97 times
Contact:

### Re: require() a file next to LUA file

hmmm....did you try dofile() ?

danell
Posts: 36
Joined: Mon Dec 12, 2016 6:32 am
Been thanked: 1 time

### Re: require() a file next to LUA file

dofile() worked but I had to hardcode the path. If I simply wrote the filename it says "cannot open testLua.lua: No such file or directory". But it's better than nothing at least!
I wonder where it's looking for the file...

Midgardsormr
Fusionator
Posts: 1053
Joined: Wed Nov 26, 2014 8:04 pm
Location: Los Angeles, CA, USA
Been thanked: 61 times
Contact:

### Re: require() a file next to LUA file

Assuming the script is in one of your Fusion Scripts folders, you could use the pathmap. If I recall correctly, comp:MapPath("Scripts:") will expand it.

Movalex
Fusioneer
Posts: 108
Joined: Fri Nov 03, 2017 5:36 am
Been thanked: 22 times
Contact:

### Re: require() a file next to LUA file

If you still want to use require(), why not check if the module you want to import is in package.path?
check ==package.path in a Console.
1. package.path = package.path .. ";\\path\to\file\?.lua;"
and then try
1. require('module')

danell
Posts: 36
Joined: Mon Dec 12, 2016 6:32 am
Been thanked: 1 time

### Re: require() a file next to LUA file

1. package.path = package.path .. ";\\path\to\file\?.lua;"

did wonders! Exactly what I wanted it to do.

To make my life easier I added this to my code to make it more portable:

1. function SplitFilename(strFilename)
2.   -- Returns the Path, Filename, and Extension as 3 values
3.   return string.match(strFilename, "(.-)([^\\]-([^\\%.]+))\$")
4. end
5.
6. local scriptPath = string.sub(debug.getinfo(1).source, 2, -1)
7.
8. package.path = package.path .. ";" .. SplitFilename(scriptPath) .. "?.lua;"
9.
10. require('secondLua')
11. print(secondLuaVariable)

Note that local variables will be local to that file only and can't be read by the main lua file or other requested files (as it should be) and requested files can't read variabels from the main file, local or not.