lua - 有没有办法打印表格的参考?
问题描述
所以我有这个清单
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)
。
目标是能够打印我放在函数中的任何列表,所以我不想在那里硬编码“数字”。我将非常感谢您的帮助,因为我觉得我已经碰到了一堵砖墙。
解决方案
在您的示例中,如果您使用名称引用表,您也可以只打印该名称。
所以只需调用类似的东西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
甚至可以为您打印内容。
推荐阅读
- mysql - 如何评价一个表在数据库系统中的好坏?
- postgresql - PostgreSQL 服务器从 9.x 升级到 10 最简单的方法
- r - R - visreg 没有正确使用 glm
- html - 如何删除垂直堆叠的两个 div 之间的空间?
- aws-lambda - Lambda 无法连接到 VPC 中的 RDS
- git - 尝试在 windows 上使用 git 连接到远程机器时,使用正确的命令,没有响应
- selenium - 带有 Selenium 的 Chrome 驱动程序
- vb.net - vb.net - 检查Datagridview中是否有重复数据
- logging - 尝试在 TensorBoard 上记录 CNN TensorFlow 的准确性
- python-3.x - python beautifulsoup4 提取特定数据