首页 > 解决方案 > 有没有办法打印表格的参考?

问题描述

所以我有这个清单

numbers = { "one", "two", "three" }

我正在尝试将其打印为

The table "numbers" contains the following entries: one, two, three

我想不通的是如何将表名转换为字符串以按我想要的方式打印出来。这是我迄今为止尝试过的:

function displayList(name)
   listName = tostring(name) -- I've also tried tostring(self)

   echo("The contents of \""..listName.."\" are: "..table.concat(name, ", "))
end

这会返回The contents of "table: 0000000000eb9c30" are: one, two, three,或者The contents of "nil" are: one, two, three如果我使用它tostring(self)

目标是能够打印我放在函数中的任何列表,所以我不想在那里硬编码“数字”。我将非常感谢您的帮助,因为我觉得我已经碰到了一堵砖墙。

标签: lua

解决方案


在您的示例中,如果您使用名称引用表,您也可以只打印该名称。

所以只需调用类似的东西displayList("numbers", numbers)

对于全局表,您可以构建一个查找表,例如

local nameLUT = {}
for k,v in pairs(_G) do
  nameLUT[v] = k
end

所以

numbers = {1,2,3}
print(nameLUT[numbers])

会打印"numbers"

更好的方法是通过元方法为您的表命名。

function nameTable(t, name)
  return setmetatable(t, {__tostring = function() return name end})
end


numbers = nameTable({"one", "two", "three"}, "numbers")

print("Table " .. tostring(numbers) .. " contains " .. table.concat(numbers, ", "))

当然,您可以使用string.format更高级的格式,__tostring甚至可以为您打印内容。


推荐阅读