nn3112337
nn3112337

Reputation: 599

How to navigate with .lua to a directory above

I have something like this.

/config.lua
/client/init.lua

How can I include the config.lua with include() or dofile()? Lg

Upvotes: 5

Views: 5475

Answers (2)

furq
furq

Reputation: 5788

You can (and probably should) do this with require by adding ../?.lua to package.path, like so:

package.path = package.path .. ";../?.lua"
require "config"

See the require and package.path docs for more info.

Upvotes: 5

Ryan Stein
Ryan Stein

Reputation: 8000

You're on the right track with dofile. (However, there is no include function in Lua.) As you may have noticed, you can't do this with require:

local cfg = require'../config'

require typically works from the directory of the initial script in a one-way direction, and any required modules which require their own modules must use relative names from that starting point to work properly.

I.e., if you have the following structure:

--+ main.lua          requires 'lib.test1'
  +-- lib/test1.lua   requires 'test2'
  +-- lib/test2.lua

test1.lua will fail to require test2 because it cannot be found from the initial directory. lib.test2 is the appropriate module name here. I'm not sure if there are any good patterns for this, short of writing your own stateful require, but it's helpful to know about when writing library code.

Perhaps it's a bad sign when it comes to this.


Going back to the question, you could make an exemption for your config file in package.loaded. This is effectively loading it manually:

package.loaded.config = dofile'../config.lua'
-- ...
local cfg = require'config'

Upvotes: 0

Related Questions