原文連結:http://blog.csdn.net/zhangxaochen/article/details/8086647
1. 先說 io.write() vs. print(), 舉例如下:看這裡: http://is.gd/VoBVUJ
io.write("sin(3)= ", math.sin(3), '\n') ----- 輸出 sin(3)= 0.14112000805987
函數的參數個數可變, 只要使用逗號分隔即可。 不過參數不能是 nil, 否則報錯, 像這樣:
lua: hello.lua:4: bad argument #4 to 'write' (string expected, got nil)
io.write 這麼用也是對的:
io.write(a..b..c) ----".." 表示串連兩個字串
這跟 io.write(a, b, c) 的輸出效果相同。但是我們應該避免第一種寫法, 原因是“..”字串串連行為會消耗更多的資源。
print 函數的調用會附加一些格外的格式, 比如:
print(a,b)
他會在 a,b 之間插入 \t 定位字元, 並且結尾自動斷行符號; 另外 print 會自動調用參數的 tostring 方法, 因此他可以調試的時候輸出 table, function, nil。
注意: io.write 因為原樣輸出參數, 沒有調用 tostring, 因此如果像這樣: io.write({}) 也會報錯,說參數應該是 string, 不能是 table
2. 簡單 I/O 模式
io.write, io.read 是一對。 預設情況下, 他們從 stdin 讀輸入, 輸出到 stdout。
另有兩個函數可以改變這一預設行為:
io.input("xx"), io.output("yy")
他們改變輸入為某個 xx 檔案, 輸出到 yy 檔案。 舉例:
-----寫在 hello.lua 裡: io.input("hello.lua") t=io.read("*all") io.write(t, '\n') ------輸出整個 hello.lua 檔案的內容到 stdin
這裡 io.read() 的參數 "*all" 表示讀取整個檔案作為一個字串。 類似有:
"*all" →讀取整個檔案
"*line" →讀取下一行
"*number" →從字串中轉換出一個數值
num →讀取 num 個字元
如果 io.read() 沒有參數, 預設讀取一行
原文連結:http://blog.csdn.net/zhangxaochen/article/details/8086647
{{OVER}}