-- 两个横线开始单行的注释
--[[
????? 加上两个[和]表示
????? 多行的注释。
--]]
----------------------------------------------------
-- 1. 变量和流控制。
----------------------------------------------------
num = 42? -- 所有的数字都是double。
-- 别担心,double的64位中有52位用于
-- 保存精确的int值; 对于需要52位以内的int值,
-- 机器的精度不是问题。
s = 'walternate'? -- 像Python那样的不可变的字符串。
t = "双引号也可以"
u = [[ 两个方括号
??????? 用于
??????? 多行的字符串。]]
t = nil? -- 未定义的t; Lua 支持垃圾收集。
-- do/end之类的关键字标示出程序块:
while num < 50 do
?? num = num + 1? -- 没有 ++ or += 运算符。
end
-- If语句:
if num > 40 then
?? print('over 40')
elseif s ~= 'walternate' then? -- ~= 表示不等于。
?? -- 像Python一样,== 表示等于;适用于字符串。
?? io.write('not over 40n')? -- 默认输出到stdout。
else
?? -- 默认变量都是全局的。
?? thisIsGlobal = 5? -- 通常用驼峰式定义变量名。
?? -- 如何定义局部变量:
?? local line = io.read()? -- 读取stdin的下一行。
?? -- ..操作符用于连接字符串:
?? print('Winter is coming,' .. line)
end
-- 未定义的变量返回nil。
-- 这不会出错:
foo = anUnknownVariable? -- 现在 foo = nil.
aBoolValue = false
--只有nil和false是fals; 0和 ''都是true!
if not aBoolValue then print('twas false') end
-- 'or'和 'and'都是可短路的(译者注:如果已足够进行条件判断则不计算后面的条件表达式)。
-- 类似于C/js里的 a?b:c 操作符:
ans = aBoolValue and 'yes' or 'no'? --> 'no'
karlSum = 0
for i = 1,100 do? -- 范围包括两端
?? karlSum = karlSum + i
end
-- 使用 "100,1,-1" 表示递减的范围:
fredSum = 0
for j = 100,-1 do fredSum = fredSum + j end
-- 通常,范围表达式为begin,end[,step].
-- 另一种循环表达方式:
repeat
?? print('the way of the future')
?? num = num - 1
until num == 0