Lua 的打印如何工作以及 Lua/Torch 中的 `__tostring` 和 `__tostring__` 有什么区别

How does Lua's print work and what is the difference between `__tostring` and `__tostring__` in Lua/Torch

我注意到有一个 __tostring__ sometimes used in Torch. In my torch-dataframe project I have a __tostring 可以处理 print(my_data)。它的工作方式与原始 Torch 中的预期完全一样,但是当我 运行 iTorch 时,它还会打印原始基础数据-table,就好像它打印了一个单独的 return 语句一样。

查看文档后,我发现 Torch 经常使用 __tostring__,因此我很好奇它们之间的区别是什么?更好地理解 Lua 中的 print 调用也很有趣,来自 R 所有 类 都能够定义自己的 print.class 来巧妙地处理输出并且没有副作用,例如我在上面的 iTorch 案例中看到的副作用。

默认情况下会发生如下情况:

[...] print always calls tostring to format its output.) However, when formatting an object, tostring first checks whether the object has a metatable with a __tostring field. If this is the case, tostring calls the corresponding value (which must be a function) to do its job, passing the object as an argument. Whatever this metamethod returns is the result of tostring

来自 PiL, 13.3.

示例:

> t = setmetatable({}, {__tostring = function(x) return "foo" end})
> print(t)
foo

当您使用 Torch class system an appropriate metatable is created. When __tostring is called this metatable will look for __tostring__, and if found, the corresponding function will be used (for more details see: these parts).

示例:

 > do local Foo = torch.class("Foo"); function Foo:__tostring__() return "this is foo" end end
 > f = Foo(); print(f)
 this is foo

因此,如果您实施自定义 Torch class,您只需覆盖 __tostring__,因为 Torch 会处理其余部分。

更新

Why iTorch adds the additional print statement to its output?

iTorch 需要 torch/env which replaces the default print function。这就是解释您获得的输出的原因。