← Back to Lua Course | Chapter 5: Functions | Lesson 3 of 7

Variable Arguments का उपयोग

तीन dots एक function को किसी भी संख्या में arguments accept करने देते हैं।

In this page:

  1. Variable Arguments

Variable Arguments

इसकी parameter list में ... के साथ declared एक function variadic है। इसके अंदर, ... एक expression list है, और select("#", ...) count देता है जबकि select(n, ...) position n से आगे के arguments return करता है। table.pack(...) या {...} इन्हें एक table में collect करता है। जब कुछ arguments nil हों तब भी select से count सही होता है।

Note: जब arguments nil हो सकते हैं तो {...} की बजाय table.pack(...) इस्तेमाल करें, क्योंकि यह n record करता है।

उदाहरण: Variable arguments

lua
local function sum(...)
  local total = 0
  for _, v in ipairs({...}) do total = total + v end
  return total
end
print(sum(1, 2, 3, 4))

local function count(...)
  return select("#", ...)
end
print(count(), count(nil, nil), count(1, 2, 3))
print(select(2, "a", "b", "c"))
print(select(-1, "a", "b", "c"))

-- Output:
-- 10
-- 0	2	3
-- b	c
-- c
{# 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. {...} इस्तेमाल करना और nil values pass होने पर # trust करना
  2. सीधे ... index करने की कोशिश करना
  3. यह भूल जाना कि ... सिर्फ एक vararg function के अंदर valid है
चैप्टर सारांश
  • ... एक function को variadic बनाता है
  • select("#", ...) arguments count करता है
  • select(n, ...) n तक skip करता है
  • table.pack n के साथ nils safely रखता है

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.