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

查看:16
本文介绍了打印 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! ;-)

Upvalues 是来自外部作用域的局部变量,用于当前函数.它们既不在 _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天全站免登陆