← Back to Lua Course | Chapter 4: Tables | Lesson 2 of 7

Arrays और Length Operator

Lua arrays index 1 से शुरू होते हैं, और # बताता है कि एक sequence में कितने items हैं।

Arrays और Length Operator

1 से n तक keys वाली एक table को sequence कहते हैं। Length operator # एक sequence में items की संख्या return करता है, जो t[#t + 1] को append करने का एक तरीका बनाता है। अगर table में holes हैं, # का result reliable नहीं है, इसलिए arrays के अंदर nil से बचें।

Note: जब एक list में nil values हो सकती हैं तो table.pack या एक explicit count field इस्तेमाल करें।

उदाहरण: Arrays and the length operator

lua
local fruits = {"apple", "banana", "cherry"}
print(#fruits, fruits[1], fruits[#fruits])
fruits[#fruits + 1] = "date"
print(#fruits)
print(fruits[0], fruits[10])
fruits[#fruits] = nil
print(#fruits)

-- Output:
-- 3	apple	cherry
-- 4
-- nil	nil
-- 3
{# 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. Arrays को 0 से शुरू करना
  2. nil holes वाले एक array पर # trust करना
  3. बीच से एक element remove करने के लिए nil assign करना और sequence तोड़ देना
चैप्टर सारांश
  • Arrays 1 से शुरू होते हैं
  • #t एक sequence की length देता है
  • t[#t+1] append करता है
  • Holes # को unreliable बना देते हैं

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.