Required Lua Relative Path

I am writing a Lua script and trying to use require in a file that exists in the same directory as the main script. It doesn't seem to me that I need to work in this case, and I tried several solutions that I found, but none of them work. I have the following files together in a directory:

main.lua
helper.lua

I tried the following solutions and got the following error:

Solution 1:

local folderOfThisFile = (...):match("(.-)[^%.]+$") 
local helper = require(folderOfThisFile .. 'helper')

lua: ...domizerWPF\DataFiles\LUA\main.lua:2: attempt to index local 'pathOfThisFile' (a nil value)
stack traceback:
    ...domizerWPF\DataFiles\LUA\main.lua:2: in main chunk
    [C]: ?

Solution 2:

package.path = "/?.lua;" .. package.path 
local helper = require('helper')

lua: ...domizerWPF\DataFiles\LUA\main.lua:2: module 'helper' not found:
    no field package.preload['helper']
    no file '/helper.lua'
    no file '.\helper.lua'
    no file 'C:\Program Files (x86)\Lua\5.1\lua\helper.lua'
    no file 'C:\Program Files (x86)\Lua\5.1\lua\helper\init.lua'
    no file 'C:\Program Files (x86)\Lua\5.1\helper.lua'
    no file 'C:\Program Files (x86)\Lua\5.1\helper\init.lua'
    no file 'C:\Program Files (x86)\Lua\5.1\lua\helper.luac'
    no file '.\helper.dll'
    no file '.\helper51.dll'
    no file 'C:\Program Files (x86)\Lua\5.1\helper.dll'
    no file 'C:\Program Files (x86)\Lua\5.1\helper51.dll'
    no file 'C:\Program Files (x86)\Lua\5.1\clibs\helper.dll'
    no file 'C:\Program Files (x86)\Lua\5.1\clibs\helper51.dll'
    no file 'C:\Program Files (x86)\Lua\5.1\loadall.dll'
    no file 'C:\Program Files (x86)\Lua\5.1\clibs\loadall.dll'
stack traceback:
    [C]: in function 'require'
    ...domizerWPF\DataFiles\LUA\main.lua:2: in main chunk
    [C]: ?

I tried solution 2 options with various paths such as "? .Lua;" and "./?lua;" to no avail.

+4
source share
3 answers

These two lines of error message shed light on your problem:

no file '/helper.lua'
no file '.\helper.lua'

package.path. , "/helper.lua", , . package.path "helper.lua" . , , main.lua.

, , main.lua helper.lua, "C:\\path\\to\\your\\lua\\project\\?.lua" package.path

+3

lua, , API , , , .

local cwd="C:\users\user\Desktop\"
dofile(cwd.."program.lua")

,

+1

, require d, ( main.lua):

local base_path = string.match(arg[0], '^(.-)[^/\\]*$')
package.path = string.format("%s;%s?.lua", package.path, base_path)

, , , require . Lua (Python , 2.6 ); , . base_path . , , SQLite, , :

local database_filename = base_path .. 'db.sqlite'

You can also make it base_pathglobal so that it is available to other modules, if necessary.

0
source

Source: https://habr.com/ru/post/1568949/


All Articles