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