reference:
http://www.lua.org/manual/5.3/manual.html
print (···)
Receives any number of arguments and prints their values to stdout
, using the function to convert each argument to a string. print
is not intended for formatted output, but only as a quick way to show a value, for instance for debugging. For complete control over the output, use and.
tostring (v)
Receives a value of any type and converts it to a string in a human-readable format. (For complete control of how numbers are converted, use.)
If the metatable of v
has a __tostring
field, then tostring
calls the corresponding value with v
as argument, and uses the result of the call as its result.
示例:
a = {5, 6}print(a)--用c来做Metatablec = {}c.__tostring =function(set) local s = "{" local sep = "" for _,e in pairs(set) do s = s .. sep .. e sep = ", " end return s .. "}" endsetmetatable(a, c)print(a)
执行结果:
table: 0x1041150{5, 6}
注释:
1. 调用第一个打印print(a),表示a为一个table,以及对应的地址。即print 函数调用 tostring 来格式化的输出。
2.调用第二个打印print(a),结果为__tostring的返回值。即当格式化一个对象的时候,tostring 会首先检查对象是否存在一个带有__tostring 域的 metatable。如果存在则以对象作为参数调用对应的函数来完成格式化,返回的结果即为 tostring 的结果。