Paul Gilmore
Paul Gilmore

Reputation: 478

Lua require not working

I am trying to make one lua file require another. I am following this guide: http://lua-users.org/wiki/ModulesTutorial

My basic test, which should be a trivial hello world, does not work, and I can't figure out why.

Here's a console log which shows all files and all errors:

C:\Users\TestUser\Desktop\LuaTest>dir
 Volume in drive C has no label.
 Volume Serial Number is XXXX-XXXX

 Directory of C:\Users\TestUser\Desktop\LuaTest

11/15/2017  03:03 PM    <DIR>          .
11/15/2017  03:03 PM    <DIR>          ..
11/15/2017  02:53 PM    <DIR>          Bar
11/15/2017  03:04 PM                92 BazModule.lua
11/15/2017  02:53 PM    <DIR>          Foo
11/15/2017  03:08 PM               139 main.lua
               2 File(s)            231 bytes
               4 Dir(s)  253,774,073,856 bytes free

C:\Users\TestUser\Desktop\LuaTest>lua main.lua
lua: main.lua:1: module 'BazModule' not found:
        no field package.preload['BazModule']
        no file 'C:\dev\LuaDist\bin'
        no file '.\BazModule.dll'
        no file 'C:\dev\LuaDist\bin\..\lib\lua\BazModule.dll'
        no file 'C:\dev\LuaDist\bin\..\lib\lua\loadall.dll'
stack traceback:
        [C]: in function 'require'
        main.lua:1: in main chunk
        [C]: ?

C:\Users\TestUser\Desktop\LuaTest>type main.lua
local baz = require("BazModule")
baz.Baz()

local bar = require("Bar.BarModule")
bar.Bar()

local foo = require("Foo.FooModule")
foo.Foo()

C:\Users\TestUser\Desktop\LuaTest>type BazModule.lua
local BazModule = {}

function BazModule.Baz()
    print("Hello Baz!")
end

return BazModule

C:\Users\TestUser\Desktop\LuaTest>lua -v
Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio

The expected output should be

Hello Baz!
Hello Bar!
Hello Foo!

But it can't find any of the files adjacent to main.lua and I don't understand why.

Upvotes: 10

Views: 19350

Answers (1)

nobody
nobody

Reputation: 4264

require searches in directories listed in package.path (for Lua files) and package.cpath (for compiled libraries).

Your error message…

lua: main.lua:1: module 'BazModule' not found:
        no field package.preload['BazModule']
        no file 'C:\dev\LuaDist\bin'
        no file '.\BazModule.dll'
        no file 'C:\dev\LuaDist\bin\..\lib\lua\BazModule.dll'
        no file 'C:\dev\LuaDist\bin\..\lib\lua\loadall.dll'

indicates the paths that require searched in. It seems that package.path is completely empty, or maybe there's a single malformed path pattern in there. (Which would be C:\dev\LuaDist\bin.)

The way the search for a module foo.bar works is that ? is substituted by foo/bar (or foo\bar – depending on OS) and so ./?.lua would find ./foo/bar.lua.

So the way to fix this is to (a) fix the place where you (or something that you installed) are/is mangling the package.path (via environment variable, startup script, …?) and/or (b) add the current directory to the search path.

Upvotes: 13

Related Questions