Search code examples
luatorchluarocks

How to correctly require lua packages using interactive lua or torch session?


I'm having difficulty installing and requiring packages in general. For example, for the inspect.lua package, I first install via luarocks as instructed in the package (https://github.com/kikito/inspect.lua):

luarocks install inspect

Then if I start either lua or torch7 (th), I will then require it via:

local inspect = require 'inspect'

This inspect variable is always nil:

require 'inspect'; print(inspect)

returns nil.

Initially, I wasn't sure that it was returning nil, so when I would try, for example inspect(1) I would get the error "attempt to call global 'inspect' (a nil value)".

Using torch, it seems like I can use "import 'inspect'" successfully, although I'm not sure why this works and require does not.

What am I doing wrong?


Solution

  • Credit for spotting that goes to @siffiejoe.

    The Lua interpreter works in blocks. Every block is treated as a separate execution set. Thus, if you write:

    local a = 5
    local b = a
    

    In a file, it will correctly set b to be equal to 5, because a lua file is treated as one big block. In the REPL, though, after the first line local variables are purged.

    That simply means you either should force your code into one block:

    do local inspect = require 'inspect'; print(inspect) end
    

    Or use a global variable that persists across block executions:

    $ inspect = require 'inspect'
    $ print(inspect)