问题
What is the Lua equivalent of the Octave/Matlab/IPython "whos" command? I'm trying to learn Lua interactively and would like to see what variables are currently defined.
回答1:
All global variables in Lua reside in a table available as global variable _G (yes, _G._G == _G). Therefore if you want to list all global variable, you can iterate over the table using 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 Lua base functions and modules. You can filter them out by checking for a value in a table which you can create on startup when no global variables other than Lua-provided are 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 as follows:
$ 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 bit tougher - you have to use Lua's debug facilities - but given that you want to use it interactively, you should only need globals.
来源:https://stackoverflow.com/questions/9892696/equivalent-of-matlab-whos-command-for-lua-interpreter