루아에서 함수는 일급객체이다. 즉 숫자형과 문자열처럼 함수를 변수에 저장할 수 있다.
a = {log = print}
a.log("Hello World")
foo = function(x)
return 2 * x
end
network = {
{name = "grauna", IP = "210.26.30.34},
{name = "arraial", IP = "210.26.30.23"},
{name = "lua", IP = "210.26.23.12"},
{name = "derain", IP = "210.26.23.20"},
}
table.sort(network, function (a, b) return (a.name > b.name) end)
function derivative (f, delta)
delta = delta or 1e-4
return function (x)
return (f(x + delta) -f(x) / delta)
end
end
c = derivative(math.sin)
print(math.cos(5.2), c(5.2))
--> 0.46851, 0.46851
Lib = {
goo = function (x, y) return x * y end
}
Lib.foo = function (x, y) return x + y end
function Lib.bar (x, y) return x - y end
-- local function goo () print("goo") end
-- local goo; goo = function() print("goo") end
local foo
local function bar()
return foo
end
function foo()
print("local foo")
end
names = {"Peter", "Paul", "Mary"}
grades = {Mary = 10, Paul = 7, Peter = 8}
function sortByGrade (names, grades)
table.sort(names, function (i, j)
return grades[i] > grades[j]
end)
end
function newCounter()
local count = 0
return function()
count = count + 1
return count
end
end
c1 = newCounter()
print(c1()) --> 1
print(c1()) --> 2