Search code examples
luaintrospectiontorch

How can I use the torch REPL for debugging?


For quick debugging it is sometimes useful to start a REPL from a script at a certain break-point. I have found out that I can start the Torch REPL at any point by:

require "trepl"
repl()

The only problem with this approach is that the REPL does not see any local variables from the calling chunk. Without being able to inspect locals, the REPL is not really useful as a debugger.

Is it possible to start a REPL which has access to local variables?

Disclaimer: I have found my own (newbie) solution to this problem, but I'm always open for alternatives/suggestions.


Solution

  • One possible workaround is to use a wrapper, which copies the local variables of the calling scope to the global scope by using debug.getlocal before calling repl():

    require "trepl"
    
    function debugRepl(restoreGlobals)
      restoreGlobals = restoreGlobals or false
    
      -- optionally make a shallow copy of _G
      local oldG = {}
      if restoreGlobals then
        for k, v in pairs(_G) do
          oldG[k] = v
        end
      end
    
      -- copy upvalues to _G
      local i = 1
      local func = debug.getinfo(2, "f").func
      while true do
        local k, v = debug.getupvalue(func, i)
        if k ~= nil then
          _G[k] = v
        else
          break
        end
        i = i + 1
      end
    
      -- copy locals to _G
      local i = 1
      while true do
        local k, v = debug.getlocal(2, i)
        if k ~= nil then
          _G[k] = v
        else
          break
        end
        i = i + 1
      end
    
      repl()
    
      if restoreGlobals then
        _G = oldG
      end
    end
    

    Note (since it is not mentioned in the documentation and only visible from the source): Typing break in the REPL returns execution to the script, while exit (or CTRL+D) terminates the execution completely.