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

Lua 复制代码
-- 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中有一种特色的线程,称为coroutine,协同线程,简称协程。其可以在运行时暂停执行,然后转去执行其他线程,然后还可以返回再继续执行没有完毕的内容。即可以"走走停停,停停走走"

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

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 复制代码
--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)

协同函数:

Lua 复制代码
cf= coroutine.wrap(
  function(a,b)
  print(a,b)
  return a+b,a*b
  end
)

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

结果:

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()

结果:

相关推荐
学步_技术1 小时前
Python编码系列—Python组合模式:构建灵活的对象组合
开发语言·python·组合模式
o独酌o1 小时前
递归的‘浅’理解
java·开发语言
Book_熬夜!1 小时前
Python基础(六)——PyEcharts数据可视化初级版
开发语言·python·信息可视化·echarts·数据可视化
waterHBO2 小时前
R语言 基础笔记
开发语言·笔记·r语言
m0_631270402 小时前
高级c语言(五)
c语言·开发语言
2401_858286112 小时前
53.【C语言】 字符函数和字符串函数(strcmp函数)
c语言·开发语言
程序猿练习生2 小时前
C++速通LeetCode中等第5题-无重复字符的最长字串
开发语言·c++·leetcode
2401_858120262 小时前
MATLAB中的无线通信系统部署和优化工具有哪些
开发语言·matlab
MATLAB滤波2 小时前
【PSINS】基于PSINS工具箱的EKF+UKF对比程序|三维定位|组合导航|MATLAB
开发语言·matlab
2401_858120532 小时前
MATLAB在嵌入式系统设计中的最佳实践
开发语言·matlab