问题描述
假设我有一段代码,如下所示
Assuming I have a piece of code such as the following
aTable = {aValue=1}
aTable_mt = {}
print(aTable)
我该怎么做才能使Lua打印类似aTable current aValue = 1
而不是table: 0x01ab1d2
的内容.
What must I do to make Lua print something like aTable current aValue = 1
as opposed to table: 0x01ab1d2
.
到目前为止,我已经尝试设置__tostring
元方法,但是print
似乎并未调用该方法.是否有我缺少的元方法,或者答案与元方法无关?
So far I've tried setting the __tostring
metamethod but that doesn't seem to be invoked by print
. Is there some metamethod I've been missing or does the answer have nothing to do with metamethods?
推荐答案
__tostring
可行:
aTable = {aValue=1}
local mt = {__tostring = function(t)
local result = ''
for k, v in pairs(t) do
result = result .. tostring(k) .. ' ' .. tostring(v) .. ''
end
return result
end}
setmetatable(aTable, mt)
print(aTable)
这将打印aValue 1
(带有一个额外的空格,请以真实代码将其删除). aTable
部分不可用,因为aTable
是引用表的变量,而不是表本身的内容.
This prints aValue 1
(with one extra whitespace, remove it in real code). The aTable
part is not available, because aTable
is a variable that references the table, not the content of the table itself.
这篇关于我们如何更改打印显示表格的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!