Lua语法

1、Lua保留的关键字:

and,bread,do,else,elseif,end,false,for,function,if,in,local,nil,not,or,repeat,return ,then,true,until,while

2、字符串多行显示

a = [[multiple line
with ''single' and "double" quoted strings inside.]]

3、支持同时定义多个变量

a,b,c,d = 1,2,"louis","song";

4、奇葩的交换值

a,b=b,a;
print(a,b);--输出2,1

5、用..连接字符串和数字

a,b = 123,"louisong";
print("a="..a,"b="..louissong);--输出a=123 b="louissong"

6、输出

print "Hello Lua!"
print ("Hello Lua!");

7、标准输入输出,不换行

io.write("hello!")
io.write("hello!")
--output--
hellohello

8、创建表

有点类似as3的Object,创建后可以通过.和[]引用其属性

a = {}
b = {1,2,3}
c = {"a","b"}
a.name = "louissong"
a.adress = "ShangHai"
print(a.name,a["adress"]);

9、if条件语句else

a=1
if a==1 then
    print("a is one")
else
print("a is not one!");
end

10、多重条件用elseif

if a==1 then
    print("a is 1")
elseif a==2 then
    print(a is 2)
else 
    print(a is 3);
end

11、条件表达式

a = 1
b = (a == 1) and "good" or "bad"
print(b)
--output--
good

12、while语法

a = 1
while a~=5 do --Lua里面用~表示不等于,类似其他语言的!
    a=a+1
    io.write(a)
end

13、repeat untile语法

a = 0
repeat
    a = a+1
    print(a)
until a == 5

14、for循环

for a=1,4 do
    io.write(a)
end
print()
for a=1,6,3 do 
    io.write(a) 
end

遍历table

t = {1,"fds",3,4}
print(t[2])
for key,value in pairs(t) do
    print(key,value)
end

15、break语法

a = 0
while true do
    a = a+1
    if(a == 10) then
        break
    end
end
print(a)

16、函数,关键字function

function test()
    print("hello")
end

test() --output hello

function test2(num)
    if(num > 3) then
        return "good"
    else
        return "bad"
    end
end

a = test2(3)
print(a); --output hello bad

17、所有的变量默认为全局的,方法里面的变量也不例外,若要声明局部变量,在变量前加local关键字