生产者-消费者
function producer()
return coroutine.create(
function (salt)
local t = { 1, 2, 3 }
for i = 1, #t do
salt =
coroutine.yield(t[i] + salt)
end
end
)
end
function consumer(prod)
local salt = 10
while true do
local running, product =
coroutine.resume(prod, salt)
salt = salt * salt
if running then
print(product or "END!")
else
break
end
end
end
consumer(producer())
结果:
11
102
10003
END!
[Finished in 0.5s]
面向对象的调用
function createFoo(name)
local data = { name = name }
local obj = {}
function obj.SetName(name)
data.name = name
end
function obj.GetName()
return data.name
end
return obj
end
o = createFoo("Sam")
print("name:", o.GetName())
o.SetName("Lucy")
print("name:", o.GetName())
print("name:", o.GetName())
结果:
name: Sam
name: Lucy
name: Lucy
[Finished in 0.1s]
lua中的setmetatable
local t = {}
local t2 = { a = " and ", b = "Li Lei", c = "Han Meimei" }
local m = { __index = t2}
setmetatable(t, m) --设表m为表t的元表
print(t.b,t.a,t.c)
结果:
Li Lei and Han Meimei
[Finished in 0.1s]
lua中的正则表达式
local uri = "http://aaaa.api.bbbb.com/user_pic/get?b_auto_id=1111&user_id=2222"
local pmatch = string.gmatch( uri,"/?([%l%d-_]+)/?" )
for w in pmatch do
print(w)
end
http
aaaa
api
bbbb
com
user_pic
get
b_auto_id
1111
user_id
2222
[Finished in 0.1s]
local s = "hello world from lua"
local d = "hello = world, from= lua"
for w in string.gmatch(d, "%a+%s*=%s*%a+") do
print(w) --匹配0个或者多个空白符
end
--
hello = world
from= lua
[Finished in 0.1s]
------
local s = "hello world from lua"
local d = "hello = world, from = lua"
for w in string.gmatch(d, "%a = %a") do
print(w)
end
--
o = w
m = l
[Finished in 0.1s]
local s = "hello world from lua"
local d = "hello = world, from = lua"
for w in string.gmatch(d, "%a+ = %a+") do
print(w)
end
---
hello = world
from = lua
[Finished in 0.1s]
table的赋值
local a = {}
a.b = {} -- 不能加local,会报错的,否则就相当于有创建了一个新的表,
table.insert(a.b,33) --table中a对应的v为一个数组{33,22,44}
table.insert(a.b,22)
-- a.m = c
table.insert(a.b,44)
for k,v in pairs(a.b) do
print(k,v)
end
结果:
1 33
2 22
3 44
求一个数组中的值对应的个数
local result = {}
local object = {23,22,33,23,55,66,23}
for i=1,#object do -- 因为要返回的result是个空表,让数组object中的值作为一个新表result的k,那么 相同key对应的v可以汇集起来
result[object[i]] = (result[object[i]] or 0) + 1 -- 相同的k默认为1,如果相同的key遍历2次就增加一个
end
print(result[23])
--
结果:3