栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

LUA学习笔记

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LUA学习笔记

Lua的API手册
  1. 变量声明:类似python,默认为全局变量,局部变量需要加上local关键字,可多重赋值,未赋值变量默认为nil(类似NULL)
a = 10
local b = 0x20--十六进制表示方法
c,d = 3e6,1e10--科学计数法 
e = tonumber("789")--转换成数字
  1. 运算符:
a = 2^6--2的6次方
b = 2<<3--左移
c = 2>>3--右移动
d = true--true或者false,只有false和nil代表假
c = 1~=1--不等号
a and b--与运算
a or b--非运算
not a--取反
b = b > 1 and 0 or 1--三元运算
  1. 字符串
str1 = "abcdn"--字符串声明,单引号双引号都可以,支持转义字符
str2 = 'abcd'
str3 = str1..str2--字符串拼接
str4 = [[asd1af4a896f416naf41]]--这种字符串声明方式不会进行转义
str5 = tostring(123)--转换成字符串
len = #str1--获取长度
s = string.char(0x10,0x11,0x12)
--[[
ascii转字符串,0x00不会影响字符串长度,也会输出为一个奇怪的字符
]]
n = string.byte(s,2)--取出第二个字符的ascii值
--或者可以这么写
n = s:byte(2)--第一个参数会传入冒号前面的变量
  1. 函数声明:(类似js)
function add(a,b)
	return a+b
end
--可返回多个值
f = function(a,b)
	return a,b
end
  1. 数组:下标从1开始
a = {1,"abc",{2,3}}
b = a[1] 
a[5] = 5--可以跨下标赋值,但a长度不会变

table.insert(a,8)--从末尾插入
table.insert(a,4,4)--从某个位置插入
table.remove(a,2)--从某个位置移除
a = {11,22,13,41,45,-68}
table.sort(a, function(a,b) return a>b end)--排序(必须是同种类型才行)
  1. 表(类似与在里面声明变量,然后归类到一起)_G是全局表,里面包含了所有声明的全局变量
a = {
    a=1,
    b="123",
    c = {1,2,3}
}
print(a['a'])--可以用变量名访问
print(a.a)--可以用.号访问
  1. 分支判断与循环
if a>b then
	...
elseif a > c then
	...
else
	...
end

--for循环里i为只读
for i=1,10 do--运行10次,i每次+1
	...
	if i>10 then--break语句
		break
	end
end

for i=1,10,2 do--运行5次,i每次+2
	...
end

while n>1 do
	n=n-1
end
  1. 多文件引用
--假设存在test.lua这个文件
require("test")--会直接执行test.lua
require("Test.test")--Test目录下的test.lua
ret = require("test")--在test.lua里可以返回值
--多次require同一文件只会运行一次

--使用方法:
--test.lua:
local test = {}
function test.Add(a,b)
	return a+b
end

return test

--main.lua
test = require("test")
test.Add(1,2)
  1. 迭代器
--[[
迭代器,遍历数组arr,下标给index(名字任意),值给val(名字任意)
遇到值为nil的变量就退出
遍历表只需要把ipairs改为pairs,index会变成变量名字
]]
for index,val in ipairs(arr) do
 	...
end


  1. 元表
t = {num = 21}
mt = {
	__add = function(a,b)
		return a.num + b
	end,
}
setmetatable(t,mt)
print(t + 3)
--[[
相当于重载加法函数,__add叫元方法。
更多元方法可以看官方文档
]]
  1. 协程(与Unity的类似,更多用法看官方文档)
f = function(a,b)
    n = 0
    while(n<100) do
        print(n+a+b)
        n=n+1
        coroutine.yield(n)--   里面可以填返回值
    end
end

cor = coroutine.create(f)--创建一个协程
--[[
    启动协程
    第一个参数为coroutine.create(f)返回的对象,其他为f所需的参数,没有可以不填
    第一个返回值为true或false,其他可自定义
]]
ret,num = coroutine.resume(cor,1,2)
print("ret:",ret," num:",num)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/997828.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号