Lua io.write() 對比 print 函數, 簡單 I/O 模式

來源:互聯網
上載者:User

 原文連結: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}}
 
 
 
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.