无法使用Lua导入模块,导致尝试索引全局“测试"(nil值) [英] Cannot import module with Lua, results in attempt to index global 'test' (a nil value)
问题描述
没有成功,我尝试使用require关键字将自己的Lua文件导入其他脚本,但是每当我尝试调用导入模块中包含的任何函数(例如"test.lua")时,我都会遇到随后的错误:>
Without success I have attempted to import my own Lua files into other scripts using the require keyword but whenever I attempt to call any functions contained within the imported module (e.g. "test.lua") I reach the subsequent error:
require 'test'
test.method(args)
==> yields error:
==> Attempt to index global 'test' (a nil value)
我已经将文件添加到package.path中,以防出现问题,但是再次没有开始错误,表明它无法在Lua的路径中找到该文件.
I've added the file to the package.path in case this was the issue, but again there was no beginning error indicating that it cannot find the file in Lua's pathway.
package.path = package.path .. ";/path/to/test.lua"
require 'test'
test.method(args)
==> yields error:
==> Attempt to index global 'test' (a nil value)
我正在从文件所在的目录运行交互式Lua Shell.尝试打印局部变量名称时,例如本地测试=要求测试"值为零.
I'm running an interactive Lua shell from the directory where the file is. When attempting to print the local variable name, e.g. local test = require "test" the value is nil.
package.path = package.path .. ";/path/to/test.lua"
local test = require 'test'
print(test)
==> nil
有什么想法吗? (注意:一般来说,我也需要文件而不将其分配给局部变量,并再次使用nil作为返回值打印其值.)
Thoughts? (Note: I also required the file in general without assigning it to a local variable and printed its values again with nil as the returned value.)
推荐答案
扩展lhf的答案:
Lua shell一次读取一个语句.然后,它使用loadstring
函数(或更准确的说是C API等效函数)加载代码字符串,该函数编译Lua代码并返回执行该代码的函数.由于每个语句分别加载,并且产生不同的功能,因此它们不共享局部变量.
The Lua shell reads one statement at a time. It then loads the code string with the loadstring
function (or more accurately, the C API equivalent), which compiles the Lua code and returns a function that executes it. Since each statement is loaded separately, and produces a different function, they don't share local variables.
本质上,此控制台输入:
Essentially, this console input:
local test = require "test"
print(test)
if test then
bar()
end
已翻译为:
(function() local test = require "test" end)()
(function() print(test) end)()
(function()
if test then
bar()
end
end)()
(请注意,这也适用于文件.Lua'files'实际上只是具有隐式function(...)
签名的函数.这意味着您可以从文件的顶层返回,也可以执行您所执行的任何操作也可以处理文件上的功能(沙盒等).
(Note that this applies to files as well. Lua 'files' are actually just functions with an implicit function(...)
signature. This means you can return from the top-level of a file, as well as perform any operations you can do on functions (sandboxing, etc) on files as well.)
如果您要从某处复制代码,则可以将代码包围在do ... end
中,如下所示:
If you're copying code from somewhere, you can surround the code in do ... end
, like so:
do
local test = require "test"
print(test)
end
do ... end
块被视为一条语句,并且作用域局部变量.
The do ... end
block counts as one statement, and scopes local variables.
这篇关于无法使用Lua导入模块,导致尝试索引全局“测试"(nil值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!