使用dofile和require的联合

在我的当前项目中,我试图通过在 main.lua 的顶部执行 dofile() 来全局添加一些语法。然后,我需要一个使用我正在尝试在项目中作为全局添加的文件,但是当我这样做时,我会收到一个 尝试索引全局值 的错误。

例如,在下面的示例中,我使用 dofile() 试图使 test1:hello() 在我的项目中全局可用,在需要 test2.lua 的过程中,我收到以下错误:

PANIC: unprotected error in call to Lua API (test2.lua: attempt to index global 'test1' (a nil value))

在这种情况下,test1 不应该已经存在于全局吗?我该如何解决这个问题?

main.lua:

dofile('test1.lua')
require('test2')

test1.lua

test1 = {}
function test1:hello()
   print("hello")
end

test2.lua

module('test2')

test1:hello()

原文链接 https://stackoverflow.com/questions/10079445

点赞
stackoverflow用户312586
stackoverflow用户312586

我刚刚测试了这段代码(在纯 Lua 5.1 中),在我的机器上运行良好(但我需要将require('test2.lua')替换为require('test2'))。

也许这是你的环境问题。你是在哪里执行这段 Lua 代码?它允许全局声明吗?

如果允许,那么听起来你并没有像你在问题中所说的那样做。

检查这些问题:

  • dofile('test1.lua') 确实在require('test2.lua')之前执行
  • 变量名是否正确(例如,你没有在某个地方将tset1写成了test1
2012-04-09 20:56:41
stackoverflow用户1208078
stackoverflow用户1208078

在 main.lua 中:

require("test2.lua")

应该改为:

require("test2")

而在 test2.lua 中,我必须将 package.seeall 作为第二个参数传递给 module(),这样它才能看到 test1 中的值。

module('test2', package.seeall)
test1:hello()
2012-04-09 21:05:58