注释:单行注释:--
多行注释:--[[    --]]

lua -l[fileName] --执行完lua后进入交互模式; 如果单纯要执行某个就 lua my.lua 


 lua script a b c 

 在运行以前,Lua使用所有参数构造arg表。脚本名索引为0,脚本的参数从1开始增加。脚本前面的参数从-1开始减少。 

 prompt> lua -e "sin=math.sin" script a b 

 arg表如下: 

 arg[-3] = "lua" 

 arg[-2] = "-e" 

 arg[-1] = "sin=math.sin" 

 arg[0] = "script" 

 arg[1] = "a" 

 arg[2] = "b" 



 他只有一个值:nil;一个全局变量没有被赋值以前默认值为nil;给全局变量负nil可以删除该变量。 


 Booleans条件中除了false和nil为假,其他值都为真。所以Lua认为0和空串都是真。 


 lua中字符串是不允许修改的,可以创建一个新的字符串用来保存老的字符串修改。 


 !!!Lua自动进行内存分配和释放,一个string可以只包含一个字母也可以包含一本书,Lua可以高效的处理长字符串,1M的string在Lua中是很常见的。可以使用单引号或者双引号表示字符串 



 print(10 .. 20)      --> 1020 ..在Lua中是字符串连接符,当在一个数字后面写..时,!!必须!! 加上空格以防止被解释错 

 print("100" + 1)    --> 101 


 tonumber()/tostring()/io.read() 

 反之,可以调用tostring()将数字转成字符串,这种转换一直有效: 

 print(tostring(10) == "10")     --> true 

 print(10 .. "" == "10")         --> true 



 为了避免不一致的结果,混合比较数字和字符串,Lua会报错,比如:2 < "15" 




 !!!!!and    or     not 这个不是 C 语言中的 与 或 非操作!! 

 not的结果只返回false或者true;逻辑运算符认为false和nil是假(false),其他为真,0也是true. 

 print(not nil)           --> true 

 print(not false)         --> true 

 print(not 0)             --> false 

 print(not not nil)       --> false 


 a and b            -- 如果a为false,则返回a,否则返回b 

 a or  b        -- 如果a为true,则返回a,否则返回b 


 table[表的使用]: 


 list风格初始化和record风格初始化是这种一般初始化的特例:其中record方式的key是变量名称加上 双引号 

 {x=0, y=0}        <-->       {["x"]=0, ["y"]=0} 

 {"red", "green", "blue"}  <-->  {[1]="red", [2]="green", [3]="blue"} 


 如果真的想要数组下标从0开始: 

 days = {[0]="Sunday", "Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday"} 

 注意:不推荐数组下标从0开始,否则很多标准库不能使用。 


 在构造函数的最后的","是可选的,可以方便以后的扩展。 

 a = {[1]="red", [2]="green", [3]="blue",} 

 在构造函数中域分隔符逗号(",")可以用分号(";")替代,通常我们使用分号用来分割不同类型的表元素。 

 {x=10, y=45; "one", "two", "three"} 



 给block划定一个明确的界限:do..end内的部分。当你想更好的控制局部变量的作用范围的时候这是很有用的。 

 do 

     local a2 = 2*a 

     local d = sqrt(b^2 - 4*a*c) 

     x1 = (-b + d)/a2 

     x2 = (-b - d)/a2 

 end            -- scope of 'a2' and 'd' ends here 

 print(x1, x2) 



 Lua语法要求break和return只能出现在block的结尾一句(也就是说:作为chunk的最后一句,或者在end之前,或者else前,或者until前) 

 有时候为了调试或者其他目的需要在block的中间使用return或者break,可以显式的使用do..end来实现: 



 如果我们只想要string.find返回的第二个值。一个典型的方法是使用哑元(dummy variable,下划线): 

 local _, x = string.find(s, p) 


 我们可能需要几个固定参数加上可变参数 

 function g (a, b, ...) 

 end 


 CALL              PARAMETERS 

 g(3)              a=3, b=nil, arg={n=0} 

 g(3, 4)           a=3, b=4, arg={n=0} 

 g(3, 4, 5, 8)     a=3, b=4, arg={5, 8; n=2} 



 Lua提供高级的require函数来加载运行库。粗略的说require和dofile完成同样的功能但有两点不同: 

 1. require会搜索目录加载文件 

 2. require会判断是否文件已经加载避免重复加载同一文件。由于上述特征,require在Lua中是加载库的更好的函数。 



 断言的处理 

 n = io.read() 

 assert(tonumber(n), "invalid input: " .. n .. " is not a number")