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

结果:

相关推荐
Aric_Jones1 小时前
lua入门语法,包含安装,注释,变量,循环等
java·开发语言·git·elasticsearch·junit·lua
Akiiiira1 小时前
【日撸 Java 三百行】Day 12(顺序表(二))
java·开发语言
EndingCoder2 小时前
2025年JavaScript性能优化全攻略
开发语言·javascript·性能优化
码上淘金6 小时前
【Python】Python常用控制结构详解:条件判断、遍历与循环控制
开发语言·python
Brilliant Nemo6 小时前
四、SpringMVC实战:构建高效表述层框架
开发语言·python
格林威8 小时前
Baumer工业相机堡盟工业相机的工业视觉中为什么偏爱“黑白相机”
开发语言·c++·人工智能·数码相机·计算机视觉
橙子199110168 小时前
在 Kotlin 中什么是委托属性,简要说说其使用场景和原理
android·开发语言·kotlin
androidwork8 小时前
Kotlin Android LeakCanary内存泄漏检测实战
android·开发语言·kotlin
学地理的小胖砸8 小时前
【Python 基础语法】
开发语言·python
DanB2410 小时前
Java笔记4
java·开发语言·笔记