Lines पर Iteration
io.lines और file:lines आपको एक file पर एक बार में एक line loop करने देते हैं।
In this page:
Lines पर Iterate करना
file:lines एक open file की lines पर एक iterator return करता है, और io.lines(path) file open करता है, iterate करता है और अंत में इसे automatically close करता है। हर line newline character के बिना आती है। यह बड़ी files के लिए memory friendly है क्योंकि एक समय में सिर्फ एक line hold होती है।
Note:
अगर file open न हो सके io.lines एक error raise करता है, इसलिए जब file शायद exist न करे इसे pcall में wrap करें।
उदाहरण: Iterating lines
local path = "/tmp/lua_demo_lines.txt"
local w = assert(io.open(path, "w"))
w:write("alpha\nbeta\n\ngamma\n")
w:close()
local n = 0
for line in io.lines(path) do
n = n + 1
print(n, "[" .. line .. "]")
end
print(pcall(io.lines, "/tmp/definitely_missing_file.txt"))
-- Output:
-- 1 [alpha]
-- 2 [beta]
-- 3 []
-- 4 [gamma]
-- false cannot open file '/tmp/definitely_missing_file.txt' (No such file or directory)
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- यह भूल जाना कि lines newline strip करता है
- बिना pcall के एक missing file पर io.lines इस्तेमाल करना
- जब एक line loop काफी हो पूरी file को memory में पढ़ना
चैप्टर सारांश
- io.lines(path) file auto-close करता है
- file:lines एक open file पर iterate करता है
- Lines में newline शामिल नहीं होता
- बड़ी files के लिए अच्छा है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: