如何使用交互式 lua 或 torch 会话正确要求 lua 包?

Jon*_*han 3 lua luarocks torch

一般来说,我在安装和需要软件包时遇到困难。例如,对于inspect.lua包,我首先按照包中的说明通过luarocks安装(https://github.com/kikito/inspect.lua):

luarocks install inspect
Run Code Online (Sandbox Code Playgroud)

然后,如果我启动luatorch7 ( th),我将通过以下方式需要它:

local inspect = require 'inspect'
Run Code Online (Sandbox Code Playgroud)

该检查变量始终是nil

require 'inspect'; print(inspect)
Run Code Online (Sandbox Code Playgroud)

返回nil

最初,我不确定它是否正在返回nil,因此当我尝试时,例如inspect(1)我会收到错误“尝试调用全局‘检查’(零值)”。

使用火炬,似乎我可以成功使用“import 'inspect'”,尽管我不确定为什么这有效,而 require 却不起作用。

我究竟做错了什么?

Bar*_*icz 5

感谢@siffiejoe的发现。

Lua 解释器以块的方式工作。每个块都被视为一个单独的执行集。因此,如果你写:

local a = 5
local b = a
Run Code Online (Sandbox Code Playgroud)

在文件中,它会正确设置b为等于 5,因为 lua 文件被视为一个大块。但在 REPL 中,在第一行局部变量被清除之后。

这仅仅意味着您要么应该将代码强制放入一个块中:

do local inspect = require 'inspect'; print(inspect) end
Run Code Online (Sandbox Code Playgroud)

或者使用在块执行中持续存在的全局变量:

$ inspect = require 'inspect'
$ print(inspect)
Run Code Online (Sandbox Code Playgroud)