[Learning lua] Module 'library' not found

I’m new with lua and have a trouble with require function.

OS: Windows 11
Lua version: Lua 5.4.2
Installed with: scoop install lua

Lua_project/
        |--- library.lua
        |--- test.lua

library.lua

local Mod = {}

function Mod.add(num1, num2)
    return num1 + num2
end

return Mod

test.lua:

local Mod = require('library')
print(Mod.add(1, 2))

In test.lua, I tried to import the module from library.lua at the same directory with it. When I run

lua test.lua

it has an error:

C:\Users\hungpham\scoop\apps\lua\current\lua54.exe: test.lua:1: module 'library' not found:
        no field package.preload['library']
        no file 'C:\Users\hungpham\scoop\apps\lua\current'
        no file 'C:\Users\hungpham\scoop\apps\lua\current'
stack traceback:
        [C]: in function 'require'
        test.lua:1: in main chunk
        [C]: in ?
shell returned 1

How can I fix this? Thanks for your help.

By default Lua does not search the current working directory for Lua files. You will have to adjust the package.path variable, either directly or through the LUA_PATH environment variable.

https://www.lua.org/manual/5.1/manual.html#pdf-require
https://www.lua.org/manual/5.1/manual.html#pdf-package.path

On Unix I can do package.path = './?.lua;' .. package.path to add the current directory, I don’t know what the pattern is on Windows, but you can probably find it in the Lua manual.

1 Like

Thank you a lot, it worked on Windows too.