在 Lua 中只归档一次

发布于 2024-08-03 20:52:38 字数 144 浏览 4 评论 0原文

我想知道是否有一种方法可以只执行一次 lua 文件,并且后续尝试执行该 lua 文件将导致无操作。

我已经考虑过做一些类似于 C++ header 的 #if/else/endif 技巧的事情。我想知道是否有一个标准方法来实现这一点。

詹姆斯

I was wondering if there's a way to do a lua file only once and have any subsequent attempts to do that lua file will result in a no-op.

I've already thought about doing something akin to C++ header's #if/else/endif trick. I'm wondering if there's a standard way to implement this.

James

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

坏尐絯 2024-08-10 20:52:38

好吧,require 几乎可以做到这一点。

require "file" -- runs "file.lua"
require "file" -- does not run the "file" again

well, require pretty much does that.

require "file" -- runs "file.lua"
require "file" -- does not run the "file" again
对你的占有欲 2024-08-10 20:52:38

require 的唯一问题是它适用于模块名称,而不是文件名。特别是, require 不处理带有路径的名称(尽管它确实使用 package.path 和 package.cpath 来定位文件系统中的模块)。

如果您想处理带有路径的名称,您可以编写一个简单的 dofile 包装器,如下所示:

do
  local cache={}
  local olddofile=dofile
  function dofile(x)
    if cache[x]==nil then
      olddofile(x)
      cache[x]=true
   end 
  end
end

The only problem with require is that it works on module names, not file names. In particular, require does not handle names with paths (although it does use package.path and package.cpath to locate modules in the file system).

If you want to handle names with paths you can write a simple wrapper to dofile as follows:

do
  local cache={}
  local olddofile=dofile
  function dofile(x)
    if cache[x]==nil then
      olddofile(x)
      cache[x]=true
   end 
  end
end
羁〃客ぐ 2024-08-10 20:52:38

基于lhf的答案,但是利用package,您也可以执行一次:

package.preload["something"]=dofile "/path/to/your/file.lua"

然后使用:

local x=require "something"

再次获取预加载的包。但这有点欺负人了...

based on lhf's answer, but utilising package, you can also do this once:

package.preload["something"]=dofile "/path/to/your/file.lua"

and then use:

local x=require "something"

to get the preloaded package again. but that's a bit abusive...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文