Give an example to introduce the basic usage of functions in Lua

Time:2021-11-29
Copy codeThe code is as follows:
function fib(n)
  if n < 2 then return 1 end
  return fib(n – 2) + fib(n – 1)
end

 

 

Copy codeThe code is as follows:
–Supports closures and anonymous functions:
function adder(x)
  — When adder is called, a function for return will be created, and the value of variable x can be remembered:
  return function (y) return x + y end
end
a1 = adder(9)
a2 = adder(36)
print(a1(16))  –> 25
print(a2(64))  –> 100

 

 

Copy codeThe code is as follows:
–Return values, function calls, and assignments can all use lists with mismatched lengths.
–Mismatched receivers will be assigned nil;
–Mismatched senders are ignored.

 

x, y, z = 1, 2, 3, 4
–Now x = 1, y = 2, z = 3, and 4 will be discarded.

 

 

Copy codeThe code is as follows:
function bar(a, b, c)
  print(a, b, c)
  return 4, 8, 15, 16, 23, 42
end

 

x, y = bar(‘zaphod’)  –> prints “zaphod  nil nil”
–Now x = 4, y = 8, and values 15.. 42 are discarded.

 

 

Copy codeThe code is as follows:
–Functions are first-class citizens and can be local or global.
–The following are equivalent:
function f(x) return x * x end
f = function (x) return x * x end

 

 

Copy codeThe code is as follows:
–These are also equivalent:
local function g(x) return math.sin(x) end
local g; g  = function (x) return math.sin(x) end
–‘local G’ can support g self reference.

 

 

Copy codeThe code is as follows:
–By the way, trigonometric functions are in radians.

 

 

Copy codeThe code is as follows:
–Call the function with a string parameter without parentheses:
print ‘hello’   — Can work.

Recommended Today

On the mutation mechanism of Clickhouse (with source code analysis)

Recently studied a bit of CH code.I found an interesting word, mutation.The word Google has the meaning of mutation, but more relevant articles translate this as “revision”. The previous article analyzed background_ pool_ Size parameter.This parameter is related to the background asynchronous worker pool merge.The asynchronous merge and mutation work in Clickhouse kernel is completed […]