Lua 有趣的语法特性

3k 词

使用函数作为函数返回

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function  (t)
local i = 0
local n = table.getn(t)
return function ()
i=i+1
if i <= n then return t[i] end
end
end

t = {1,2,7,8}

for e in list_iter(t) do
print(e)
end

table关联数组的多种访问形式

1
2
3
4
5
u = {name=rming,age=25,hello='hi~'}

print(u.hello)
-- 关联数组形式
print(u['hello'])

table计数的问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
-- 一个nil元素的时候,碰到nil就停止计数了
t = {1,2,3,nil}
print(#t)
print(table.getn(t))
-- 多个nil的时候就没有规律了
t = {1,2,3,nil,nil,6}
print(#t)
t = {1,2,3,nil,nil,6,nil}
print(#t)
-- 这个key,不认识了,没有计数
t = {[2]=1}
print(#t)
-- 所以,计数还是自己写个吧
t_count = function(t)
local count = 0
for i,v in pairs(t) do
if v then
count = count+1
end
end
return count
end
print(t_count(t))

函数其实也是变量

1
2
s = {p=print}
s.p('halo')

local 和 global 函数在调用的时候会有所区别

1
2
3
4
5
6
7
8
9
10
local f
f = function()
print('this is a local function')
end
local function f()
print('this is a local function')
end
function gf()
print('this is a global function')
end

可变参数(5.1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
local f = function( ... )
local arg = {...}
print('------------------------')
for i,v in pairs(arg) do
print(v)
end
print('------------------------')

--[[
for v in ... do
print(v)
end
]]
end
f(1,2,3,4,5,6,7)

参数默认值

1
2
3
4
5
6
7
local function ff(name,age)
name = name or 'rming'
age = age or 20
print(name)
print(age)
end
ff()

三元表达式

1
2
3
-- a==b ? 'yes' : 'no'
res = a==b and 'yes' or 'no'
print(res)

不同变量类型比较时不存在自动转换

1
2
3
4
5
6
7
8
9
print('0'==0)
--false
print('2'<'15')
--false
--tostring() 和 tonumber() 是不错的解决办法
print(tonumber('0')==0)
--true
print(tostring(0)=='0')
--true

只有 nilfalse 是假,0,{},"" 都是真

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> if nil then print('true') else print('false') end
false
> if false then print('true') else print('false') end
false
> if 0 then print('true') else print('false') end
true
> if {} then print('true') else print('false') end
true
> if '' then print('true') else print('false') end
true

print(not nil) --> true
print(not false) --> true
print(not 0) --> false
print(not not nil) --> false

for循环

1
2
3
4
-- print all values of array 'a'
for i,v in ipairs(a) do print(v) end
-- print all keys of table 't'
for k in pairs(t) do print(k) end

对象方法的调用

1
2
3
4
5
> a={p=print}
> a:p('hello')
table: 0x7fa95bf00510 hello
> a.p('hello')
hello

函数多个返回值

1
2
3
> s,e=string.find('this is a string ', 'string')
> print(s,e)
11 16

泛型调用和 unpack

1
2
3
4
5
6
7
8
9
10
11
> f = string.find
> t = {'this is a string', 'is'}
> print(f(unpack(t)))
3 4
-- unpack的lua实现
function unpack(t, i)
i = i or 1
if t[i] then
return t[i], unpack(t, i + 1)
end
end

高级函数 和 函数的本质

Lua中的函数是带有词法定界的第一类值().

1
2
3
4
5
6
7
8
9
-- 高级函数
table.sort(network, function (a,b)
return (a.name > b.name)
end)

-- 函数定义仅仅是赋值
func = function(v)
print v
end

多行字符串

1
2
3
4
5
6
7
8
9
10
local page = [[
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>xxxx</title>
</head>
<body>
</body>
</html>
]]
print(page)