在lua中获取函数参数的名称

Uiy*_*Uiy 3 lua

当调用 lua 函数时

PrintMe(MyVariableName)

我希望能够实际打印“MyVariableName”而不是它的值(好吧,出于演示目的)。

显然我可以只传递字符串,但这需要额外的引号,我也想打印它的值。

例如,

MyVariable = 4
PrintVariable(MyVariable)
Run Code Online (Sandbox Code Playgroud)

会打印“MyVariable is 4”或其他什么

我不想重复名称和变量,如

PrintVariable(MyVariable, "MyVariable")
Run Code Online (Sandbox Code Playgroud)

因为这是不必要的重复。

lua可以处理吗?

我现在正在做的是在引号中传递变量名称并使用 loadstring 来获取值,但我只想直接传递变量而不使用额外的不必要的引号(我认为 debug.getlocal 做到了,但最终返回了值而不是名字)。


这是模拟示例

function printme1(var, val)
    print(var.." = "..val)
end

function printme2(v)
    local r
    loadstring("r = "..v)() -- equivalent to r = a but must be used since v is a string representing a and not the object a
    print(v.." = "..tostring(r))
end

function printme3(v)
    -- unknown
end

a = 3

printme1("a", a)
printme2("a")
printme3(a) 
Run Code Online (Sandbox Code Playgroud)

在这种情况下,所有 3 个都应该打印相同的内容。printme3 显然是最方便的。

Mud*_*Mud 5

您不能说PrintVariable(MyVariable),因为 Lua无法让您确定使用哪个变量(如果有;可以使用常量)将参数传递给您的函数。但是,您可以PrintVariable('MyVariable')then 使用调试 API 在调用者的范围内查找具有该名称的局部变量:

function PrintVariable(name)
  -- default to showing the global with that name, if any
  local value = _G[name]

  -- see if we can find a local in the caller's scope with that name
  for i=1,math.huge do
    local localname, localvalue = debug.getlocal(2,i,1)
    if not localname then
      break -- no more locals to check
    elseif localname == name then
      value = localvalue
    end
  end

  if value then
    print(string.format("%s = %s", name, tostring(value)))
  else
    print(string.format("No variable named '%s' found.", name))
  end
end
Run Code Online (Sandbox Code Playgroud)

现在你可以说:

PrintVariable('MyVariable')
Run Code Online (Sandbox Code Playgroud)

虽然在这种情况下将打印“MyVariable = 4”。


不,如果你真的想在没有引号的情况下这样做,你可以检查调用者的本地变量是否有提供的值,但如果调用者的范围中有多个变量,这偶尔会给你错误的变量名一个给定的值。话虽如此,下面是你如何做到这一点:

function PrintVariable(value)
  local name

  -- see if we can find a local in the caller's scope with the given value
  for i=1,math.huge do
    local localname, localvalue = debug.getlocal(2,i,1)
    if not localname then
      break
    elseif localvalue == value then
      name = localname
    end
  end

  -- if we couldn't find a local, check globals
  if not name then
    for globalname, globalvalue in pairs(_G) do
      if globalvalue == value then
        name = globalname
      end
    end
  end

  if name then
    print(string.format("%s = %s", name, tostring(value)))
  else
    print(string.format("No variable found for the value '%s'.", tostring(value)))
  end
end
Run Code Online (Sandbox Code Playgroud)

现在你可以说PrintVariable(MyVariable),但是如果在调用者的作用域中碰巧有另一个具有 value 的变量4,并且它发生在 之前MyVariable,那么将打印变量名。