通过相对路径加载 Lua 文件 [英] Load Lua-files by relative path

查看:29
本文介绍了通过相对路径加载 Lua 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的文件结构:

If I have a file structure like this:

./main.lua
./mylib/mylib.lua
./mylib/mylib-utils.lua
./mylib/mylib-helpers.lua
./mylib/mylib-other-stuff.lua

main.lua 文件mylib.lua 可以加载完整路径require('mylib.mylib').但是在 mylib.lua 中,我还想加载其他必要的模块,而且我不想总是指定完整路径(例如 mylib.mylib-utils).如果我决定移动文件夹,我将进行大量搜索和替换.有没有办法只使用路径的相对部分?

From main.lua the file mylib.lua can be loaded with full path require('mylib.mylib'). But inside mylib.lua I would also like to load other necessary modules and I don't feel like always specifying the full path (e.g. mylib.mylib-utils). If I ever decide to move the folder I'm going to have a lot of search and replace. Is there a way to use just the relative part of the path?

更新.如果重要的话,我将 Lua 与 Corona SDK 结合使用.

UPD. I'm using Lua with Corona SDK, if that matters.

推荐答案

有一种方法可以推导出文件的本地路径"(更具体地说,是用于加载文件的字符串).

There is a way of deducing the "local path" of a file (more concretely, the string that was used to load the file).

如果您需要 lib.foo.bar 中的文件,您可能会这样做:

If you are requiring a file inside lib.foo.bar, you might be doing something like this:

require 'lib.foo.bar'

然后,当您在所有函数之外时,您可以获取文件的路径作为第一个元素(也是唯一的)... 变量.换句话说:

Then you can get the path to the file as the first element (and only) ... variable, when you are outside all functions. In other words:

-- lib/foo/bar.lua
local pathOfThisFile = ... -- pathOfThisFile is now 'lib.foo.bar'

现在,要获取文件夹",您需要删除文件名.最简单的方法是使用匹配:

Now, to get the "folder" you need to remove the filename. Simplest way is using match:

local folderOfThisFile = (...):match("(.-)[^%.]+$") -- returns 'lib.foo.'

这就给你了.现在您可以将该字符串添加到其他文件名并使用它来要求:

And there you have it. Now you can prepend that string to other file names and use that to require:

require(folderOfThisFile .. 'baz')     -- require('lib.foo.baz')
require(folderOfThisFile .. 'bazinga') -- require('lib.foo.bazinga')

如果你移动 bar.luafolderOfThisFile 会自动更新.

If you move bar.lua around, folderOfThisFile will get automatically updated.

这篇关于通过相对路径加载 Lua 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆