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

查看:138
本文介绍了通过相对路径加载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可以使用完整路径require('mylib.mylib')加载文件mylib.lua.但是在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?

UPD.如果这很重要的话,我正在使用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'

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

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天全站免登陆