Lua基础005

协同

--定义协同函数 coroutine.create
co= coroutine.create(
function (a,b)--匿名
    print(a+b)
end
)
--启动协同函数 coroutine.resume
coroutine.resume(co,20,30)-->50
--第二种定义,与,启动
c2=coroutine.wrap(
function (c,f)
    print("c=="..c.." f=="..f)
end
)
c2("fe",555)-->c==fe f==555
--暂停协同函数
co3=coroutine.create(
function(a,c)
    print(string.format("a+c=%d",a+c))
    coroutine.yield()
    print(string.format("a-c=%d",a-c))
end
)
coroutine.resume(co3,100,3)-->a+c=103
print("上面的co3已停住,要再次resume才能输出a-c");
coroutine.resume(co3)-->a-c=97

coroutine的返回值

co4=coroutine.create(
function(a,b)
    print(string.format("a==%d,b==%d",a,b))
    coroutine.yield(a+b,a/b);
    print("coroutine.yield 下的返回值 return");
    return a%b,a*b
end
)
res0,res1,res2=coroutine.resume(co4,22,5);
print(res0,res1,res2)--true 27    4.4
print("待执行coroutine下面的语句");
res4,res5,res6=coroutine.resume(co4);
print(res4,res5,res6);--coroutine.yield 下的返回值 return      true  2   110

class

Person={name="小曾",age=99}
function Person:readBook()
print(string.format("%s在读书",self.name))
end

function Person:new()
    t={}
    setmetatable(t,{__index=self})
    return t;
end

person_1=Person:new()
print("Person类的 new出来了 "..person_1.name)-->Person类的 new出来了 小曾
person_1:readBook()-->小曾在读书
print("new 出来的第二个person ----");
person_2=Person:new();
person_2.name="小曾子呀 "
print(person_2.name)-->小曾子呀 
person_2:readBook()-->小曾子呀 在读书

class写法2

Dog={age=11,gender=1}
function Dog:think()
    print("dog think "..self.age.." want to go");
end
function Dog:ctor(tab)
    t=tab or {}
    --setmetatable(t,{__index=self})--两种写法,下面那种也行
    setmetatable(t,self)
    self.__index=self;
    return t;
end

dog_1=Dog:ctor()
dog_1:think()
dog_2=Dog:ctor({weight="120kg"})
print(dog_2.weight..":"..dog_2.age)
dog_2:think()

猜你喜欢

转载自blog.csdn.net/SendSI/article/details/77825708
005