http://www.lua.org/manual/5.3/manual.htmlhtml
print (···)
Receives any number of arguments and prints their values to stdout
, using the tostring
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 string.format
andio.write
.函数
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, usestring.format
.)ui
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.lua
a = {5, 6} print(a) --用c来作Metatable c = {} c.__tostring =function(set) local s = "{" local sep = "" for _,e in pairs(set) do s = s .. sep .. e sep = ", " end return s .. "}" end setmetatable(a, c) print(a)
执行结果:spa
table: 0x1041150 {5, 6}
1. 调用第一个打印print(a),表示a为一个table,以及对应的地址。即print 函数调用 tostring 来格式化的输出。
debug
2.调用第二个打印print(a),结果为__tostring的返回值。即当格式化一个对象的时候,tostring 会首先检查对象是否存在一个带有__tostring 域的 metatable。若是存在则以对象做为参数调用对应的函数来完成格式化,返回的结果即为 tostring 的结果。code