在Lua中打印可访问当前范围的所有局部变量 [英] Print all local variables accessible to the current scope in Lua

查看:516
本文介绍了在Lua中打印可访问当前范围的所有局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何使用以下代码打印所有"全局变量

I know how to print "all" global variables using the following code

for k,v in pairs(_G) do
    print("Global key", k, "value", v)
end

所以我的问题是如何对当前执行函数可访问的所有变量执行此操作,而这些操作可以执行locals()对于Python的作用.

So my question is how to do that for all variables that are accessible from the currently executing function, something that can do what locals() does for Python.

推荐答案

此处是locals()函数的实现.它将从调用范围返回一个本地表:

Here is an implementation of a locals() function. It will return a table of locals from the calling scope:

function locals()
  local variables = {}
  local idx = 1
  while true do
    local ln, lv = debug.getlocal(2, idx)
    if ln ~= nil then
      variables[ln] = lv
    else
      break
    end
    idx = 1 + idx
  end
  return variables
end

请注意,在lua REPL中,每一行都是一个单独的块,具有单独的局部变量.此外,还返回内部变量(如果要删除它们,名称以'('开头):

Notice that in the lua REPL, each line is a separate chunk with separate locals. Also, internal variables are returned (names start with '(' if you want to remove them):

> local a = 2; for x, v in pairs(locals()) do print(x, v) end
a   2
(*temporary)    function: 0x10359b38


感谢您的接受.您已经解开了难题的最后一块! ;-)


Thanks for the accept. You have unlocked the last piece of the puzzle! ;-)

升值是外部作用域的局部变量,在当前函数中使用.它们既不在_G中也不在locals()

Upvalues are local variables from outer scopes, that are used in the current function. They are neither in _G nor in locals()

function upvalues()
  local variables = {}
  local idx = 1
  local func = debug.getinfo(2, "f").func
  while true do
    local ln, lv = debug.getupvalue(func, idx)
    if ln ~= nil then
      variables[ln] = lv
    else
      break
    end
    idx = 1 + idx
  end
  return variables
end

示例(请注意,您必须使用a才能显示该示例):

Example (notice you have to use a for it to show up):

> local a= 2; function f() local b = a; for x,v in pairs(upvalues()) do print(x,v) end end; f()
a   2

这篇关于在Lua中打印可访问当前范围的所有局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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