Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
lua:如何在uuu-tostring元方法中获得原始字符串?_Lua - Fatal编程技术网

lua:如何在uuu-tostring元方法中获得原始字符串?

lua:如何在uuu-tostring元方法中获得原始字符串?,lua,Lua,代码如下: local t = {} setmetatable(t, {__tostring = function(self) return 'MyTable is: '..tostring(self) end}) print(t) 运行代码将导致错误:“C堆栈溢出”。因为在tostring元方法中,tostring(self)将调用tostring元方法,这是一个死循环 有没有办法获取值“t”的原始字符串?要从Lua执行您试图执行的操作,您基本上必须从主表中取消设置元表,然后对其调用tost

代码如下:

local t = {}
setmetatable(t, {__tostring = function(self) return 'MyTable is: '..tostring(self) end})
print(t)
运行代码将导致错误:“C堆栈溢出”。因为在tostring元方法中,tostring(self)将调用tostring元方法,这是一个死循环


有没有办法获取值“t”的原始字符串?

要从Lua执行您试图执行的操作,您基本上必须从主表中取消设置元表,然后对其调用
tostring
,然后将元表设置回原位。像这样:

setmetatable(t, {__tostring = function(self)
  local temp = getmetatable(self)
  setmetatable(self, nil)
  local ret = 'MyTable is: ' .. tostring(self)
  setmetatable(self, temp)
  return ret
end,
})

另外,请注意,
\uu tostring
元函数应该返回字符串,而不仅仅是打印它。

如果删除tostring()调用,它就会工作。它会显示类似于
MyTable is:table:0x2132542
@Moop:我想这就是OP想要的。如果我删除tostring(),它会导致错误:尝试连接作为解决方案的表值。非常感谢。但是如果有表的保护,我就不能更改元表。@isaf:你说的“表的保护”是什么意思?只要
setmetatable
函数存在且未被修改,就没有办法阻止某人设置metatable。如果metatable有字段“\uu metatable”,它不能被setmetatable更改。但我发现它可以通过debug.setmetatable更改。@Llamageddon:这是什么意思?您根本无法从不同的线程访问相同的Lua状态,并且两个单独的Lua状态包含彼此完全断开连接的数据。因此,这并不比Lua中的任何其他构造更“线程安全”。@NicolBolas Ahhh,您确实是对的,谢谢:-P