使用dofile并需要结合使用

Chr*_*ert 1 lua

在我当前的项目中,我试图通过在我的顶部执行dofile()来全局地为我的项目添加一些语法main.lua.然后我要求第三个文件使用我试图在我的项目中添加为全局的文件; 但是我attempting to index the global value这样做会收到错误.

例如,在下面的例子中,我使用dofile处理(),企图使测试1:你好()期间需要test2.lua的过程中我的项目中全局可用,然而,我收到错误:

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

在这种情况下,test1不应该作为全局存在吗?我怎么能绕过这个?

main.lua:

dofile('test1.lua')
require('test2')
Run Code Online (Sandbox Code Playgroud)

test1.lua

test1 = {}
function test1:hello()
   print("hello")
end
Run Code Online (Sandbox Code Playgroud)

test2.lua

module('test2')

test1:hello()
Run Code Online (Sandbox Code Playgroud)

Mik*_*ran 5

在main.lua中:

require("test2.lua")
Run Code Online (Sandbox Code Playgroud)

应该:

require("test2")
Run Code Online (Sandbox Code Playgroud)

在test2.lua中我必须将package.seeall作为第二个参数传递给module(),以便它可以在test1中看到值

module('test2', package.seeall)
test1:hello()
Run Code Online (Sandbox Code Playgroud)