Lua 语言概念概况

下面是对 Lua 语言基本概念的简要概况。

查看 Lua 编程指南的第 1-5 章,了解更多详细信息。

注释
--A comment
--[[ A
comment block
]]


变量
local var1 -- Declaring a variable
local var2; -- Semicolon to end a statement (chunk) is optional
local var3 = nil -- nil is the default value for all uninitialized variables - similar to null in other languages
local VaR4 = "AbC" -- variables and strings are case-sensitive
local var5 = {} -- Declaring an array (a.k.a table)


保留的名称
and       break     do        else      elseif
end       false     for       function  if
in        local     nil       not       or
repeat    return    then      true      until
while


变量类型
local string = "Hello world"
local number = 10
local number2 = 10.4
local boolean = true
local function = type()


字符串中的逃逸字符
local string = "one line\nnext line\n\"in quotes\", 'in quotes'"


表 - 类似于其他语言中的数组
local a = {} -- create a table
local a = {1,2,3} -- accessed as a[1]=1, a[2]=2, a[3]=3
local a = {one=1,two=2,three=3} -- accessed as a["one"]=1, a["two"]=2, a["three"]=3 or a.one=1, a.two=2, a.three=3
-- items are placed starting at [1] position when declaring like this
local a = {"one","two","three"} -- accessed as a[1]="one", a[2]="two", a[3]="three"
-- replacing array items
a[1] = "four"
a["x"] = "string"
a["y"] = 5


运算符优先顺序
^ (exponential)
not  - (unary operator)
*   /
+   -
.. (concatenation)
<   >   <=  >=  ~=  == (relational operators)
and (boolean operator)
or (boolean operator)


括号控制优先顺序
(a+i) < ((b/2)+1)


串接
local b = "Hello ".."World"
local b = 0 .. 1 -- spacing required for numbers


多重赋值
a,b = 1,2
a,b = f() -- functions can return multiple results


If/then/else
if a<0 then a = 0 end
if a<b then return a else return b end


循环结构
local i = 1
while a[i] do
  print(a[i])
  i = i + 1
end


循环
for i=1,f(x) do dw.log.exception("INFO",i) end
for i=10,1,-1 do dw.log.exception("INFO",i) end
-- log all values of array 'a'
for i,v in ipairs(a) do dw.log.exception("INFO",v) end