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

Files में लिखना

write method strings और numbers को बिना newlines add किए एक file में save करता है।

Files में लिखना

file:write किसी भी संख्या में strings और numbers accept करता है और इन्हें exactly दिए गए रूप में लिखता है, इसलिए \n खुद include करें। यह file handle return करता है ताकि calls chain हो सकें। Numbers usual format से convert होती हैं, और दूसरे types को पहले tostring से convert करना ज़रूरी है।

Note: tidy, structured lines के लिए write के साथ string.format इस्तेमाल करें।

उदाहरण: Writing to files

lua
local path = "/tmp/lua_demo_write.txt"
local f = assert(io.open(path, "w"))
f:write("line one\n")
f:write("line ", 2, "\n"):write(string.format("pi is %.2f\n", math.pi))
f:close()

local r = assert(io.open(path, "r"))
print(r:read("a"))
r:close()

-- Output:
-- line one
-- line 2
-- pi is 3.14
{# 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. यह उम्मीद करना कि write एक newline add करेगा
  2. write को एक table या nil pass करना
  3. f.write("x") में colon की बजाय dot इस्तेमाल करना
चैप्टर सारांश
  • write newlines add नहीं करता
  • यह strings और numbers accept करता है
  • यह chaining के लिए file return करता है
  • colon syntax f:write इस्तेमाल करें
🔒

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.