← Back to Lua Course | Chapter 8: File I/O | Lesson 4 of 7

Lines पर Iteration

io.lines और file:lines आपको एक file पर एक बार में एक line loop करने देते हैं।

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

lua
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)
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह भूल जाना कि lines newline strip करता है
  2. बिना pcall के एक missing file पर io.lines इस्तेमाल करना
  3. जब एक 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.