(1)
for index = 1,4 do
print("hello: ",index)
end
单个命令或一系列命令组成的脚本文件,我们称为代码块(chunk),代码块可以很小,也有大到几兆的。
(2)
myString = "hello world"
print(myString)
(3)
dofile ("c:/...")
dofile命令用来执行脚本(只要不是那些包含了用C++写的LuaGlue函数就可以),参数是字符串,指定文件的名字和路径。
数字不能做起始符,也要避免下划线加大写字母,因为这种格式是为Lua自身保留的。
常量用全大写和下划线,例如:MAX_VALUE
变量第一个字母小写,例如:myString
全局变量第一个字母用g,例如:gMyGlobal
函数名第一个字母大写,例如:function MyFunction()
(4)
注释:
--this is a comment
--[[
function Counting()
for index = 1,500 do
print(index, "+", index + 1, "=", index + (index +1))
end
end
--]]
变量不需要声明,变量类型取决于我们赋的值。
(5)
可以使用type函数来判断变量类型。
myValue = 7
print(type(myValue))
Lua中有五种变量类型:
nil,boolean,string,number,table
nil类型:
用来表示这个变量还没有被赋值,如果给一个变量赋值为nil,那实际表示删除该变量的意思。
例如:local myValue --this creates a local variable with an initial nil
boolean类型:
只有两种值,true和false。
例如: myValue = true --create a boolean variable with a value of true
string类型:
例如:myValue = "hello" --a string value
lua会根据上下文在合理的情况下进行数字与字符之间的转换。
print("5" + 5)
10
number类型:
number在Lua中是双精度浮点数,Lua没有整型类型,
例如:
myValue = 2
myValue = 2.2
myValue = 2.3e8
myValue = 2.2e-2
table类型:
作为入门,我们可以把它当做数组使用。
例如:
myTable = {2,3,4}
print(myTable[3])
4
myTable[3] = 33
print(myTable[3])
33
局部变量与全局变量:
Lua变量默认是全局的,定义局部变量:local myValue = 3
变量的有效范围取决于声明变量的位置。
(6)
function MyFunc()
local x = 7
if x < 10 then
local y = "hello"
print(y)
end
print(y) --print nil,because the variable above is destroyed
end
关系运算符:
if a== b then
print("a is equal to b")
end
if a <= b then
print("")
end
如果我们使用关系类型比较table,只有两个table是同一个对象时才能得到预期的结果,因为变量只是table的引用(就像指针一样)。
例如:
table1 = {1,2,3}
table2 = {1,2,3}
if table1 == table2 then
print("==")
else
print("!=")
end
!=
例如:
table1 = {1,2,3}
table2 = table1
if table1 == table2 then
print("==")
else
print("!=")
end
==
逻辑运算符:
and,or,not(好比&&,||,!)
Lua中,false和nil会被逻辑运算符当做false,其他值为true。
例如:
if (a>2) and (a<5) then
print("")
end
if语句:
if ... then
end
if ...then
else if ...then
end
if ...then
...
else
...
end
while和repeat语句:
while:
index = 1
while index < 10 do
print("")
index = index + 1
end
repeat:
index = 1
repeat
print("")
index = index + 1
until index >10
for语句:
两种控制结构(数字型,通用型)
数字型:
for index = 1,100 do
print("")
end
我们可以在第三个参数中定义step值,例如:
for index = 10,1,-1 do
print("")
end
注意:循环次数只是在第一次执行时确定,因此,就算用户更改参数值也不会影响最终循环次数,其次,循环中的变量是局部变量,一旦循环结束就会被清除。
break语句:
从循环结构中强制退出。不能在循环外使用。