Equivalent to Matlab "whos" command for Lua translator?

What is the Lua equivalent of the Octav / Matlab / IPython "whos" command? I'm trying to learn Lua interactively and would like to see what variables are currently defined.

+3


source to share


1 answer


All global variables in Lua are in a table, accessible as a global variable _G

(yes, _G._G == _G). Therefore, if you want to list the entire global variable, you can iterate over the table with pairs()

:

function whos()
    for k,v in pairs(_G) do
        print(k, type(v), v) -- you can also do more sophisticated output here
    end
end

      

Note that this will also give you all the basic Lua functions and modules. You can filter them out by checking the value in the table, which you can create at startup if there are no non-Lua global variables defined:

-- whos.lua
local base = {}
for k,v in pairs(_G) do
    base[k] = true
end
return function()
    for k,v in pairs(_G) do
        if not base[k] then print(k, type(v), v) end
    end
end

      



Then you can use this module like this:

$ lua
Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio
> whos = require 'whos'
> a = 1
> b = 'hello world!'
> whos()
a   number  1
b   string  hello world!
whos    function    function: 0x7f986ac11490

      

Local variables are a little more complicated - you have to use Lua's debugging tools - but given that you want to use it interactively, you need global variables.

+8


source







All Articles