Values के रूप में Functions
Functions variables में store हो सकते हैं, दूसरे functions को pass हो सकते हैं और इनसे return हो सकते हैं।
In this page:
Values की तरह Functions
Lua में Functions first-class values हैं, जिसका मतलब है आप इन्हें tables में रख सकते हैं, arguments की तरह pass कर सकते हैं, और anonymously बना सकते हैं। एक function जो argument की तरह दूसरा function लेता है एक higher-order function है, जैसे एक custom map या filter। Anonymous functions function(...) ... end बिना नाम के लिखे जाते हैं।
Note:
syntax function f() end बस f = function() end के लिए sugar है।
उदाहरण: Functions as values
local function map(t, f)
local out = {}
for i, v in ipairs(t) do out[i] = f(v) end
return out
end
local squares = map({1, 2, 3}, function(x) return x * x end)
print(table.concat(squares, ","))
local ops = {
add = function(a, b) return a + b end,
mul = function(a, b) return a * b end,
}
print(ops.add(2, 3), ops.mul(2, 3))
-- Output:
-- 1,4,9
-- 5 6
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- function को call करना जब आप इसे pass करना चाहते थे
- यह भूल जाना कि एक table में store functions को ढूंढने के लिए एक key चाहिए
- यह उम्मीद करना कि anonymous functions का error messages में एक नाम होगा
चैप्टर सारांश
- Functions values हैं
- ये pass और return हो सकते हैं
- Anonymous functions का कोई नाम नहीं
- Higher-order functions functions लेते हैं
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: