包括文件、覆盖变量

发布于 2025-01-06 05:07:55 字数 535 浏览 0 评论 0原文

我试图通过在代码末尾要求第二个来覆盖第一个 .lua 文件中的变量。

file1.lua

val = 1
require "file2"

file2.lua

val = 2

不幸的是,这似乎不起作用,因为在此之后 val 仍然是 1。我想出的解决方案是允许这些文件的潜在未来用户包含文件,这是一个新函数,我现在在初始化 Lua 时插入它:

function include(file)
    dofile("path/since_dofile_doesnt_seem_to_use/package/path" .. file .. ".lua")
end

这与预期完全一样,但因为我还是新手Lua,我想知道是否有更好的解决方案。也许已经内置了一些东西?

更新:

我的问题是,我不小心在多个文件上多次需要 file2,并且 Lua 不会再次加载它来更改值。解决了。

I'm trying to overwrite the variables in my first .lua file, by requiring a second on, at the end of my code.

file1.lua

val = 1
require "file2"

file2.lua

val = 2

Unfortunately this doesn't seem to work, as val is still 1 after this. The solution I came up with, to allow the potential future users of those files to include files, is a new function, which I'm for now inserting when initializing Lua:

function include(file)
    dofile("path/since_dofile_doesnt_seem_to_use/package/path" .. file .. ".lua")
end

This works exactly as expected, but since I'm still new to Lua, I'd like to know, if there might be a better solution. Maybe there's something already build in?

Update:

My problem was that I've accidentally required file2 multiple times, over multiple files, and Lua wouldn't load it again, to change the value. Solved.

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

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

发布评论

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

评论(2

缱倦旧时光 2025-01-13 05:07:55

Lua 在名为 package.loaded 的表中跟踪代码中 require 的所有文件。每次 require 一个文件时,都会检查该表,如果表中已存在该模块名称,则不会加载该文件。如果表中不存在,则加载模块并将名称添加到表中。这样您就可以多次 require 一个模块,但它只会在第一次运行。

您可以通过在 require 包之后设置 package.loaded[packagename] = nil 来解决这个问题。这样,当lua检查表中是否存在包名时,它就不会找到它,所以你可以根据需要多次require它。

Lua keeps track of all the files you have required in your code in a table called package.loaded. Every time a file is required, that table is checked, and if the module name exists in the table already, it is not loaded. If it does not exist in the table, the module is loaded and the name is added to the table. This way you can require a module many times but it will only be run the first time.

You can get around this by setting package.loaded[packagename] = nil after requireing the package. That way, when lua checks if the package name exists in the table, it will not find it, so you can require it as many times as you want.

腹黑女流氓 2025-01-13 05:07:55

在 file2.lua 中

print(val)
_G.val = 2
print(val)

输出应该是

1

2

in file2.lua

print(val)
_G.val = 2
print(val)

output should be

1

2

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