-- create a class
Animal={name = "no_name" , age=0 }
function Animal:bark(voice)
        print(self.name.."in"..voice.."jiao")
end

function Animal:new()
    a={}
    setmetatable(a,{__index=self})
    return a
end
animal = Animal:new()
animal2=Animal:new()
-- print(animal)
-- print(animal2)

animal.name = "Tom"
animal.age = 8
animal.type = "cat"

print(animal.name.."jn"..animal.age)

function animal2:skill()
    return "mouse"
end

print(animal2.name.."jn"..animal.age..animal2:skill())

function Animal:new (obj)
        local a=obj or {}
        setmetatable(a,{__index=self})
        return a
end

Cat =Animal:new({type="bosiCat"})
Cat.eye="blue eye"
tomcat =Cat:new()
tomcat.name="Tome"
print(tomcat.name.."is".."d"..tomcat.type)

运行结果:

lua面向对象(类)和lua协同线程与协同函数、Lua文件I/O-LMLPHP

Lua协同线程

lua中有一种特色的线程,称为coroutine,协同线程,简称协程。其可以在运行时暂停执行,然后转去执行其他线程,然后还可以返回再继续执行没有完毕的内容。即可以“走走停停,停停走走”

在lua中表示独立的执行线程。任意时刻只会有一个协程执行,而不会出现多个协程同时执行的情况。

-- create thread
crt=coroutine.create(
  function(a,b)
     print(a,b,a+b)
     -- obtain running thread
     tr=coroutine.running();
     print(tr)
     -- check type
     print(type(tr))
     -- check crt  status
     print(coroutine.status(crt))
     -- coroutine pending
     coroutine.yield()
     print("back")

  end
)

-- start coroutine  a=3,b=5
coroutine.resume(crt,3,5)
-- check crt type
print("main-"..type(crt))
-- check crt  status
print("main-"..coroutine.status(crt))
-- cancel panding  math is not imporitance
coroutine.resume(crt,3,5)
-- check crt  status
print("main-"..coroutine.status(crt))

运行结果:

lua面向对象(类)和lua协同线程与协同函数、Lua文件I/O-LMLPHP

有返回值的协同线程

--create
crt=coroutine.create(
  function(a,b)
     print(a,b)
     c=a*b
     print(c)
     coroutine.yield(c,a/b)
     return a+b,a-b
    -- print("back")
  end
)

result,result1,result2 =  coroutine.resume(crt,4,7)
print(result,reslut1,result2)

协同函数:

cf= coroutine.wrap(
  function(a,b)
  print(a,b)
  return a+b,a*b
  end
)

success,result1,result2=cf(3,4)

结果:

lua面向对象(类)和lua协同线程与协同函数、Lua文件I/O-LMLPHP

Lua的IO

file= io.open("t1.lua","r")
io.input(file)
line=io.read()
print("hi")
while line ~= nil  do
   print(line)
   line=io.read("*1")
end
io.close(file)

File操作

file= io.open("t1.lua","a")
file:write("\nlevel=p7")
file:close()

结果:

12-01 22:25