Lua基础005

来源:互联网 发布:制做图表的软件 编辑:程序博客网 时间:2024/06/07 16:16

协同

--定义协同函数 coroutine.createco= coroutine.create(function (a,b)--匿名    print(a+b)end)--启动协同函数 coroutine.resumecoroutine.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=103print("上面的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*bend)res0,res1,res2=coroutine.resume(co4,22,5);print(res0,res1,res2)--true 27    4.4print("待执行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))endfunction Person:new()    t={}    setmetatable(t,{__index=self})    return t;endperson_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");endfunction Dog:ctor(tab)    t=tab or {}    --setmetatable(t,{__index=self})--两种写法,下面那种也行    setmetatable(t,self)    self.__index=self;    return t;enddog_1=Dog:ctor()dog_1:think()dog_2=Dog:ctor({weight="120kg"})print(dog_2.weight..":"..dog_2.age)dog_2:think()