Equivalent of Matlab “whos” command for Lua interpreter?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-10 10:14:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!