1.first-class
lua中的函数被称为第一类值,也就是函数能够被存储在变量中和表中,也能被当做参数传递,也能够被其它函数返回。
其中lua中的函数是没有名字的, 当我们讨论函数的名字,比如print,实际说的是变量(能够实现函数功能的变量)。
a = {p = print}
a.p("Hello World") -->Hello World
print = main.sin -->'print' now refers to the sine function
a.p(print(1)) -->0.841470
sin = a.p --- sin now refers to the print function
sin(10, 20) -->10 20
函数的创建:
function foo(x) return 2*x end
--也可以写做如下形式,并且可将其称为匿名函数。
foo = function (x) return 2*x end
table根据key元素进行排序:
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)