-- Example 21 -- repeat until statement. a=0 repeat a=a+1 print(a) until a==5 ------ Output ------ 1 2 3 4 5 -- 例子 25 -- repeat until 语句 -- Example 22 -- for statement -- Numeric iteration form. -- Count from 1 to 4 by 1 for a=1,4 do io.write(a) end print() -- Count from 1 to 6 by 3. for a=1,6,3 do io.write(a) end ------ Output ------ 1234 14 -- 例子22 -- for 语句 -- 从1到4,每次自增1 -- 从1到6,每次自增3 -- Example 23 -- More for statement -- Sequential iteration form. for key,value in pairs({1,2,3,4}) do print(key, value) end ------ Output ------ 1 1 2 2 3 3 4 4 -- 例子 23 -- 更多的for语句 -- 顺序迭代形式 -- Example 24 -- Printing tables. -- Simple way to print tables a={1,2,3,4,"five","elephant","mouse"} for i,v in pairs(a) do print(i,v) end ------ Output ------ 1 1 2 2 3 3 4 4 5 five 6 elephant 7 mouse -- 例子 24 -- 打印表 -- 简单的打印表的方式 -- Example 25 -- break statement. -- break is used to exit a loop. a=0 while true do a=a+1 if a==10 then break end end print(a) ------ Output ------ 10 -- 例子 25 -- break语句 -- break用来跳出一个循环 -- Example 26 -- Functions. -- Define a function without parameters or return value. function myFirstLuaFunction() print("My First lua function was called") end -- Call myFirstLuaFunction. myFirstLuaFunction() ------ Output ------ My first lua function was called -- 例子 26 -- 函数 -- 定义一个没有形参和返回值的方法 -- Example 27 -- More functions. -- Define a function with a return value. function mySecondLuaFunction() return "string from my second function" end -- Call function returning a value. a=mySecondLuaFunction("string") print(a) ------ Output ------ string from my second function -- 例子 27 -- 更多的函数 -- 定义一个返回一个值函数 -- Example 28 -- More functions. -- Define function with multiple parameters and multiple return values. function myFirstLuaFunctionWithMultipleReturnValues(a,b,c) return a,b,c,"My first lua function with multiple return values",1, true end a,b,c,d,e,f = myFirstLuaFunctionWithMultipleReturnValues(1,2,"three") print(a,b,c,d,e,f) ------ Output ------ 1 2 true My first lua function with multiple return values 1 true -- 例子 28 -- 更多的函数 定义一个有多个形参和返回值的函数 -- Example 29 -- Variables scoping and functions -- All variables and global in scope by default b="global" -- To make local variables you must put the keyword 'local' in front function myFunc() local b=" local variable" a="global variable" print(a,b) end myfunc() print(a,b) ------ Output ------ global variable local variable global variable global -- 例子 29 -- 变量作用域和功能 -- 所有的变量默认是全局变量 -- 为了创建一个局部变量,必须在前面用关键字local修饰 -- Example 30 -- Formatted printing. -- An implementation of printf. function printf(fmt, ...) io.write(string.format(fmt, ...)) end printf("Hello %s from %s on %s\n", os.getenv"USER" or "there", _VERSION, os.date()) ------ Output ------ Hello there from Lua 5.1 on 06/20/12 10:36:12 -- 例子 30 -- 格式化输出 -- 一个printf的实现
QuickLuaTour翻译流水账(21-30)
最新推荐文章于 2024-06-29 16:22:07 发布