Variable Arguments का उपयोग
तीन dots एक function को किसी भी संख्या में arguments accept करने देते हैं।
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- {...} इस्तेमाल करना और nil values pass होने पर # trust करना
- सीधे ... index करने की कोशिश करना
- यह भूल जाना कि ... सिर्फ एक vararg function के अंदर valid है
चैप्टर सारांश
- ... एक function को variadic बनाता है
- select("#", ...) arguments count करता है
- select(n, ...) n तक skip करता है
- table.pack n के साथ nils safely रखता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: