Search code examples
lua

Why won't lua 5.4 load a module from the current directory by default?


I see multiple questions here, that imply loading modules from the current directory should be the default behavior of Lua. See "selected answers" for these two questions:

But my experience with lua54 is that it doesn't:

C:\Code\lua\testcwd>type hello.lua
local function hello()
        print("Hello!")
end

return {hello=hello}
C:\Code\lua\testcwd>type use_hello.lua
hello = require("hello")

hello.hello()

C:\Code\lua\testcwd>type use_hello2.lua
-- Util needed by requireLocal()
local function get_directory_path(sep)
    local file_path = debug.getinfo(2, "S").source:sub(2)
    local dir_path = file_path:match("(.*" .. sep .. ")")
    if not dir_path then
        dir_path = "." .. sep
    end
    return dir_path
end

-- Enables calling require for current working directory
local function requireLocal()
    local separator = package.config:sub(1,1)

    local dir_path = get_directory_path(separator)

    package.path = package.path .. ";" .. dir_path .. "?.lua"
end

requireLocal()

hello = require("hello")

hello.hello()

C:\Code\lua\testcwd>lua54 use_hello.lua
lua54: use_hello.lua:1: module 'hello' not found:
        no field package.preload['hello']
        no file 'C:\lua\systree\share\lua\5.4\hello.lua'
        no file 'C:\lua\systree\share\lua\5.4\hello\init.lua'
        no file 'C:\lua\systree\lib\lua\5.4\hello.dll'
stack traceback:
        [C]: in function 'require'
        use_hello.lua:1: in main chunk
        [C]: in ?

C:\Code\lua\testcwd>lua54 use_hello2.lua
Hello!

C:\Code\lua\testcwd>lua54 -v
Lua 5.4.2  Copyright (C) 1994-2020 Lua.org, PUC-Rio

Why is "use_hello.lua" not merely working? One clearly sees that it does NOT search the current directory. To the best of my knowledge, my PUC lua 5.4 (Windows 10) configuration is "default". Just to load a module from the current directory, why do I need to perform this "crazy setup" of "use_hello2.lua"? Is that something that changed with lua 5.4? The readme of 5.4 doesn't seem to say this changed.


Solution

  • The problem here is that the default value of package.path is overridden by the LUA_PATH environment variable, and its value does not include ./?.lua.

    In the manual, it mentions that if you want to include the default search path in an environment variable, you can append ;; to it. This also applies to LUA_CPATH. for instance:

    C:\lua\systree\share\lua\5.4\?.lua;C:\lua\systree\share\lua\5.4\?\init.lua;;