有没有一种方法可以打印表的引用?

所以我有一个列表

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

我正在尝试将其打印为

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

我无法弄清楚如何将表名转换为字符串以按照我的想法打印它。这是我到目前为止尝试过的方法:

function displayList(name)
   listName = tostring(name) -- 我也尝试了tostring(self)

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

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

目标是能够打印我放在函数中的任何列表,因此我不想在那里硬编码"numbers"。非常感谢您的帮助,因为我感觉自己已经遇到了瓶颈。

点赞
用户2858170
用户2858170

在你的例子中,如果你指定一个表的名称,你可以直接打印这个名称。

因此,只需要调用类似于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为你输出内容。

2020-12-19 19:27:09