while
a=10
while( a < 20 )
do
print("a 的值为:", a)
a = a+1
end
for
for i=10,1,-1 do
print(i)
end
遍历
--打印数组a的所有值
for i,v in ipairs(a)
do print(v)
end
until
a = 10
--[ 执行循环 --]
repeat
print("a的值为:", a)
a = a + 1
until( a > 15 )
嵌套
j =2
for i=2,10 do
for j=2,(i/j) , 2 do
if(not(i%j))
then
break
end
if(j > (i/j))then
print("i 的值为:",i)
end
end
end
break
while( a < 20 )
do
print("a 的值为:", a)
a=a+1
if( a > 15)
then
--[ 使用 break 语句终止循环 --]
break
end
end
if
--[ 0 为 true ]
if(0)
then
print("0 为 true")
end
if( a == 10 )
then
--[ 如果条件为 true 打印以下信息 --]
print("a 的值为 10" )
elseif( a == 20 )
then
--[ if else if 条件为 true 时打印以下信息 --]
print("a 的值为 20" )
elseif( a == 30 )
then
--[ if else if condition 条件为 true 时打印以下信息 --]
print("a 的值为 30" )
else
--[ 以上条件语句没有一个为 true 时打印以下信息 --]
print("没有匹配 a 的值" )
end
函数
function max(num1, num2)
if (num1 > num2) then
result = num1;
else
result = num2;
end
return result;
end
函数赋值
Lua 中我们可以将函数作为参数传递给函数,如下实例:
myprint = function(param)
print("这是打印函数 - ##",param,"##")
end
function add(num1,num2,functionPrint)
result = num1 + num2
-- 调用传递的函数参数
functionPrint(result)
end
myprint(10)
-- myprint 函数作为参数传递
add(2,5,myprint)
多返回值
function maximum (a)
local mi = 1 -- 最大值索引
local m = a[mi] -- 最大值
for i,val in ipairs(a) do
if val > m then
mi = i
m = val
end
end
return m, mi
end
print(maximum({8,10,23,12,5}))
不等于
if( a ~= b )
then
print("Line 2 - a 不等于 b" )
else
print("Line 2 - a 等于 b" )
end
逻辑
if ( a and b )
then
print("a and b - 条件为 true" )
end
if ( a or b )
then
print("a or b - 条件为 true" )
end
if ( not( a and b) )
then
print("not( a and b) - 条件为 true" )
else
print("not( a and b) - 条件为 false" )
end
..和#
print("连接字符串 a 和 b ", a..b )
print("b 字符串长度 ",#b )
print("字符串 Test 长度 ",#"Test" )
print("w3cschool菜鸟教程网址长度 ",#"www.w3cschool.cc" )