4

usually when I have a question about something remotely software related I find that someone else has already asked the very same thing, and gotten good answers that works for me too.

This time, though, I've failed to find an answer to my predicament.

Here we go: I'm currently trying to move up my Lua-programming a notch or three and want to use modules. So, I've got a structure like this:

main.lua
foo/bar.lua

Now, in main.lua I do

require("foo.bar")

which fails,

main.lua:1 module 'foo.bar' not found:
     no field package.preload['foo.bar']
     no file 'foo.bar.lua'
     no file 'foo.bar.lua'
     no file 'foo.lua'

Ok, something might be wrong with my package.path so I use package.searchpath("foo.bar", package.path) to see what I', doing wrong.

The problem is that package.searchpath resolves foo.bar to foo/bar.lua which is exactly right.

As I've understood it, package.searchpath tries to find the module in the same way as require, but there seems to be som glitch in my case.

What strikes me as odd is the repetition of the no file 'foo.bar.lua' in the error output

Have I misunderstood the use of require?

I'm using LuaJIT-2.0.0 to run my chunks


Update:

I'm using LuaJIT-2.0.0 to run my chunks <- This was the reason for my problem, stock Lua-5.2.2 behaves as expected

sojason
  • 41
  • 4
  • 1
    Can you try it in stock Lua from lua.org? – lhf Aug 08 '13 at 13:36
  • Can you include what `package.path` is on your setup? – greatwolf Aug 08 '13 at 19:13
  • 1
    **[This](http://stackoverflow.com/questions/11714204/is-it-possible-to-make-imports-depend-on-the-location-of-my-lua-script-instead-o/18042670#18042670)** might be related. – greatwolf Aug 08 '13 at 19:15
  • @lhf, I tried it with Lua-5.2.2 and it worked as a charm... the fault lies in LuaJIT it seems. – sojason Aug 09 '13 at 08:33
  • @greatwolf , I'll try your approach to work around the problems with LuaJIT (unfortunately, changing this is not an option at the moment) – sojason Aug 09 '13 at 08:34

1 Answers1

1
package.path = debug.getinfo(1,"S").source:match[[^@?(.*[\/])[^\/]-$]] .."?.lua;".. package.path
require("foo.bar")

This line causes require to look in the same directory as the current file when asked to load other files. If you want it to instead search a directory relative to the current directory, insert the relative path between " and ?.lua

Here is part of require description:

[...] Otherwise require searches for a Lua loader using the path stored in package.path. If that also fails, it searches for a C loader using the path stored in package.cpath. If that also fails, it tries an all-in-one loader (see package.loaders).

Default path for package.path is always the .exe that executes specified script.

deepspace
  • 771
  • 3
  • 11
  • 25
  • I think that explains my problem, I'm calling the script as `../luajit main.lua`. Will verify this tomorrow! – sojason Aug 08 '13 at 20:54