LUA笔记(基础语法)

LUA笔记(基础语法)

第一课 变量
  1. Lua中,默认总是全局变量,无需声明,赋值即为创建。
       (未赋值也不会 报错,而为nil)
  print(b) ==> nil
  b = 10 ;
  print(b) ==>10

★若想删除一个全局变量,只需将变量赋值为nil 如:b=nil

  1. 变量使用前必须声明(赋值)

  2. 变量三种类型

  • 全局变量:除了local声明的局部变量都是全局变量
  • 局部变量:用local声明,如local b = 5
  • 表中的域
  1. 赋值
a = "hellow world"
t = t+1
a,b = 1,2
x,y = y,x  ps:lua中先计算右边所有参数,所以可用于交换变量值
a[i],a[j] = a[j],a[i]
第二课 数据类型
  1. nil 空,可以理解为null
    nil做比较时要加引号
type(b)  ==>nil
type(b) == nil  ==> false
type(b) == 'nil '   ==>true
  1. 布尔(Boolean)
    就是truefalse
    lua中true和其他(包括0)都为true
    falsenil看作false
  2. 数字(number)
    lua中只有一种数字类型:双精度类型
    数字全为数型(加引号除外)
  3. 字符串(string)
    a = "hellow"
    4.1 其中可用两个方括号[[---]]标识一串字符串
html = [[
 <html>
  <head> --- </head>
  <body>---</body>
 </html>
 ==>输出结果与 方括号一致
 ]]

    4.2 lua强连接符两个英文的句号

print('你好'..'LUA') ==>你好LUA
print(123..456) ==>123456

    4.3 lua中计算字符串长度

print(#"lxy")  ==>3
  1. 表(table)
    相当于一个"关联数组",数组的索引可数字可字符串.
local tab1 = { }
local tab2 = {"apple" , "c" , "d"}
  1. 函数(function)
    和其他函数类似:
function hanshu1(n)
	函数体;
end
★匿名函数
function hanshu2(x , y)
	print(x+y)
end

hanshu2(1 ,
function(z)
	y = y + z
end
)
第三课 循环
  1. while循环
    条件为true,执行循环体
    ★当条件为"true"时,既while(true)会无限循环
while(a < 5) do
	print(a)
	a=a+1
end
  1. for循环
    2.1 数值for循环
for a=1,3,1 do
print(a)
end ==>1,2,3   (即条件从处值1,增加到3,每次增加1)
//步长如果不指定,默认为1

   2.2 泛型for循环

value = {'你' , '我' , '他'}
for i,v in ipairs(value) do
print(i..":"..v)
end
==>1:, 2:, 3://其中 `iParis`为迭代函数,用于迭代数组
  1. repeat…until 循环
    先执行循环后判断条件
repeat
	print(a)
	a = a+1
until(a>3)
==>1,2,3
  1. break
    退出当前语句或循环
  2. goto
    将程序的控制点转移到另一个标签处
第四课 流程控制
  1. if 判断语句
if(布尔表达式1) then	
	print("满足布尔表达式1条件")
elseif(布尔表达式2)
	print("满足布尔表达式2条件")
	.
	.
else
	print("不满足以上条件")
end
第五课 运算符
  1. + , - , * , / ,% , ^ , _
    加,减,乘,除,求余,求幂,求负
  2. ~= , ==
    不等,等于
    3.and , or , not
    与,或,非

你可能感兴趣的:(LUA笔记(基础语法))