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

Values के रूप में Functions

Functions variables में store हो सकते हैं, दूसरे functions को pass हो सकते हैं और इनसे return हो सकते हैं।

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

lua
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
{# 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. function को call करना जब आप इसे pass करना चाहते थे
  2. यह भूल जाना कि एक table में store functions को ढूंढने के लिए एक key चाहिए
  3. यह उम्मीद करना कि anonymous functions का error messages में एक नाम होगा
चैप्टर सारांश
  • Functions values हैं
  • ये pass और return हो सकते हैं
  • Anonymous functions का कोई नाम नहीं
  • Higher-order functions functions लेते हैं

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.