相当于Matlab的“whos” Lua口译员的命令? [英] Equivalent of Matlab "whos" command for Lua interpreter?

查看:165
本文介绍了相当于Matlab的“whos” Lua口译员的命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Octave / Matlab / IPythonwhos命令的Lua等价物是什么?我正在尝试以交互方式学习Lua,并希望看到当前定义了哪些变量。

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.

推荐答案

Lua中的所有全局变量驻留在一个可用作全局变量的表中 _G (是的,_G._G == _G)。因此,如果要列出所有全局变量,可以使用对()迭代表:

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

请注意,这也将为您提供所有Lua基本功能和模块。您可以通过检查表中的值来筛选它们,当没有定义Lua提供的全局变量时,您可以在启动时创建该值:

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

局部变量有点难度 - 你必须使用< a href =http://www.lua.org/manual/5.1/manual.html#pdf-debug.getlocal =nofollow> Lua的调试工具 - 但是考虑到你想要使用它交互式地,你应该只需要全局变量。

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.

这篇关于相当于Matlab的“whos” Lua口译员的命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆