C++系列十:其他-1. Lua

系列文章目录


前言

我写这个博客的一个问题?(●’◡’●) 居然是 取名太难了。
其实都是摘抄,用vscode ,写了几行代码,写下聊表心意哈。
学习太累了,我要躺平……

Lua介绍:

脚本语言!

参考链接:

安装参考
嗨客网
菜鸟教程
C++调用lua

基本语法:

--1. 注释:
--单行注释
--[[
    多行注释
    多行注释
--]]
--2. 数据类型:
nil、boolean、number、string、function、userdata、thread、table
--3. nil删除全局变量的值:
a = 1024;print(a);a = nil;print(a)
--4. type判断变量是否为nil
a = 1024
if (type(a) == "nil")
then
	print("a is nil")
else
	print("a is not nil")
end
--5. 定义多个变量
name, age = "haicoder", 1024
--6. string("" 或 '')、块字符串([[ ]])
varname = "1024";password='123456'
varname = [[
	<body>
	    <a href="https://www.haicoder.net/">haicoder</a>
	</body>
]]
--7.全局变量(默认),局部变量(local,表中的域(???):
a = 1024
function pi()
	pi = 3.14159
	local name = "haicoder" --局部变量
end
pi();print("a =", a, "pi =", pi, "name =", name)
--8...运算符,实现字符串连接、使用 # 实现获取字符串长度、三目运算符and 和 or 
local str1 = "Hello";local str2 = " HaiCoder"
local ret = str1..str2;print(string.format("ret = %s", ret))
print(string.format("strl len = %d, str2 len = %d", #str1, #str2))
a = 100;b = 1024;local ret = a > b and a or b--只会在需要时才去操作第二个操作数
--9.模块:
module={};return module
package.path="E:\\C++\\LuaProject"..package.path;--搜索路径
local m = require("module")
--10.错误处理:
assert(type(a) == "number", "a is not a number")
assert(type(b) == "number", "b is not a number")
pcall 、debug


--详细罗列
nil	--只有值 nil 属于该类,表示一个无效值(在条件表达式中相当于 false)。
boolean	--包含两个值:false 和 true。
number	--表示双精度类型的实浮点数。(int float double )
string	--字符串由一对双引号或单引号来表示。
function	--由 C 或 Lua 编写的函数。
userdata	--表示任意存储在变量中的 C 数据结构。
thread	--表示执行的独立线路,用于执行协同程序。
table	--Lua 中的表(table)其实是一个 “关联数组”(associative arrays),数组的索引可以是数字或者是字符串。在 Lua 里,table 的创建是通过 “构造表达式” 来完成,最简单构造表达式是 {},用来创建一个空表。

函数、迭代器

--迭代器:
for迭代器
array = {"Hello", "HaiCoder", "Lua"}
for k, v in ipairs(array)
do
   print(string.format("Key = %d, Value = %s", k, v))
end

table、userdata、模块

--初始索引一般以 1 ;
--有新数据插入时长度会自动增长;
--保存数据可以是任何类型,包括 function 和 table。
--所有元素之间,总是用逗号 “,” 隔开
concat、insert、maxn、remove、sort

mytable = {}
mytable[1] = "Lua";print("mytable[1] =", mytable[1])
mytable["name"] = "haicoder";print("mytable[name] =", mytable["name"])
mytable["name"] = "HaiCoder";print("mytable[name] =", mytable["name"])

--userdata
int luaL_newmetatable(lua_State*L, const char *tname);
void luaL_getmetatable(lua_State *L,const char *tnaem); 
void *luaL_checkudata(lua_State*L,int index,const char *tname);

--模块
module={}
module.constant="this is constant"
function module.func1()
    io.write("this is a public function")
end
local function func2()
    io.write("this is private function")
end
function module.func3()
    func2()
end
return module
--调用
--package.path的路径
package.path="E:\\C++\\LuaProject"..package.path;
local m = require("module")
print(m.constant)
m.func3();

元素、元方法:

mytable = setmetatable({},{foo=2,zh="zhou"})
tty=getmetatable(mytable)    -- 这回返回mymetatable
print(tty.zhouyi)

--元方法:
 __index、__newindex、__add、__sub、__mul、__div、__mod、__unm、__concat、__eq、__lt、__le、__call、__tostring、
1. __index
mytable = setmetatable({key1 = "value1"}, {
  __index = function(mytable, key)
    if key == "key2" then
      return "metatablevalue"
    else
      return nil
    end
  end
})
print(string.format("key1 = %s, key2 = %s", mytable.key1, mytable.key2))
--简写:
mytable = setmetatable({key1 = "value1"}, { __index = { key2 = "metatablevalue" } })
print(mytable.key1,mytable.key2)

2. __newindex 

协程、文件读写

Lua 协同程序(coroutine)与线程比较类似:拥有独立的堆栈,独立的局部变量,独立的指令指针,同时又与其它协同程序共享全局变量和其它大部分东西。

coroutine.create()、coroutine.resume()、coroutine.yield()、coroutine.status()、coroutine.wrap()、coroutine.running()	、coroutine.isyieldable()

status():suspended、running、normal、dead

coco = coroutine.create(function (a,b)
    print("resume args:"..a..","..b)
    yreturn = coroutine.yield()
    print ("yreturn :"..yreturn)
end)
coroutine.resume(coco, 0, 1)
coroutine.resume(coco, 21)
--
#!/usr/bin/lua
print("haicoder(www.haicoder.net)\n")
coco2 = coroutine.wrap(function (a,b)
    print("resume args:"..a..","..b)
    yreturn = coroutine.yield()
    print ("yreturn :"..yreturn)
end)
print(type(coco2))
coco2(0,1)
coco2(21)
--
local newProductor
function productor()
     local i = 0
     while true do
          i = i + 1
          send(i)     -- 将生产的物品发送给消费者
     end
end
function consumer()
     while true do
          local i = receive()     -- 从生产者那里得到物品
          print(i)
     end
end
function receive()
     local status, value = coroutine.resume(newProductor)
     return value
end
function send(x)
     coroutine.yield(x)     -- x表示需要发送的值,值返回以后,就挂起该协同程序
end
-- 启动程序
newProductor = coroutine.create(productor)
consumer()



---文件读写
io.input([file])、io.output([file])、io.close([file])、io.read(formats)、io.lines([fn])、io.write(value)、io.flush()。

io.open(fn [, m])、io.close([file])、io.seek ([p] [, of])、、、、、、、、

m>r、w、a、r+、w+、a+、b、+、、、
seek:set,cur,end
-- 以只读方式打开文件
file = io.open("test.lua", "r")
-- 设置默认输入文件为 test.lua
io.input(file)
-- 输出文件第一行
print(string.format("read file:[%s]", io.read()))
-- 关闭打开的文件
io.close(file)
-- 以附加的方式打开只写文件
file = io.open("test.lua", "a")
-- 设置默认输出文件为 test.lua
io.output(file)
-- 在文件最后一行添加 Lua 注释
io.write("File content in test.lua")
print("file write success")
-- 关闭打开的文件
io.close(file)

-----------------
local f = io.open("3.txt", "a+")
f:write("Happy New Year!")
f:flush()
f:seek("end", -1) --定位到文件末尾前一个字节
local str = f:read(1) --读取一个字符
print(str) --输出"!"
f:close()

面向对象、垃圾回收

--面向对象:
-- 元类
Rectangle = {area = 0, length = 0, breadth = 0}
-- 派生类的方法 new
function Rectangle:new (o,length,breadth)
  o = o or {}
  setmetatable(o, self)
  self.__index = self
  self.length = length or 0
  self.breadth = breadth or 0
  self.area = length*breadth;
  return o
end
-- 派生类的方法 printArea
function Rectangle:printArea ()
  print("矩形面积为 ",self.area)
end

r = Rectangle:new(nil,10,20)
print(r.length)
r:printArea()

------ 元类
Shape = {area = 0}
-- 基础类方法 new
function Shape:new (o,side)
  o = o or {}
  setmetatable(o, self)
  self.__index = self
  side = side or 0
  self.area = side*side;
  return o
end
-- 基础类方法 printArea
function Shape:printArea ()
  print("Area is", self.area)
end
-- 创建对象
myshape = Shape:new(nil,10)
myshape:printArea()

--垃圾回收:
collectgarbage("collect"): 做一次完整的垃圾收集循环。通过参数 opt 它提供了一组不同的功能:
collectgarbage("count"): 以 K 字节数为单位返回 Lua 使用的总内存数。 这个值有小数部分,所以只需要乘上 1024 就能得到 Lua 使用的准确字节数(除非溢出)。
collectgarbage("restart"): 重启垃圾收集器的自动运行。
collectgarbage("setpause"): 将 arg 设为收集器的 间歇率。 返回 间歇率 的前一个值。
collectgarbage("setstepmul"): 返回 步进倍率 的前一个值。
collectgarbage("step"): 单步运行垃圾收集器。 步长"大小"由 arg 控制。 传入 0 时,收集器步进(不可分割的)一步。 传入非 0 值, 收集器收集相当于 Lua 分配这些多(K 字节)内存的工作。 如果收集器结束一个循环将返回 truecollectgarbage("stop"): 停止垃圾收集器的运行。 在调用重启前,收集器只会因显式的调用运行。
mytable = {"apple", "orange", "banana"}
print(collectgarbage("count"))
mytable = nil
print(collectgarbage("count"))
print(collectgarbage("collect"))
print(collectgarbage("count"))

--[[
20.9560546875
20.9853515625
0
19.4111328125
]]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

joyyi9

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值