lua的第二篇学习笔记 小程序+输出说明 --1. 逻辑比较 >,>=,<,<=, ==, ~= print( "---------1----------------") print(3.14 ~= math.pi) --> true x = x or math.pi -- 等价于 if not x then x = v end print(x) --2. table 初始化 print( "---------2----------------") t1 = { color = "blue", own="ha"; "one", "two", "three", [4] = "four" } print(t1.color) print(#t1) print(t1[1]) --3 循环语句中的局部变量作用域 print( "---------3----------------") repeat local line = math.random(1, 10) print( line ) until line >= 8 --> 在循环条件中可以访问局部变量line --4 table 的遍历 print( "---------4----------------") for i in pairs(t1) do --> 关联表数组全部打印 print(i, t1[i]) end print("----") for i, v in ipairs(t1) do --> 只打印数组 print( i, v ) end print("---") t2 = { {name = "tafjk", ip = "192.168.8.1"}, {name = "test", ip = "192.168.1.5"}, {name = "my", ip = "192.168.201.1"}, } -- table sort for i in pairs(t2) do --> 关联表数组全部打印 print(i, t2[i].name, t2[i].ip) end print( "-" ) table.sort(t2, function (obj1,obj2) return (obj1.ip > obj2.ip ) end ) for i in pairs(t2) do --> 关联表数组全部打印 print(i, t2[i].name, t2[i].ip) end --5 函数返回值 --若函数调用时最后一个参数,则会返回所有返回值,否则,只返回一个值 print( "---------5----------------") function foo() return 2009, 1 end print( foo() ) --> 2009 1 print( ( foo() ) ) --> 2009 x = foo() print( x ) --> 2009 x,y,z = foo(), "foo" --> 2009 foo nil print(x, y, z) print( unpack( { foo() } ) ) --> 2009 1, unpack接受list参数,并从下标1开始返回 print( string.format("%d-%d-%s", 2009, 1, "lua") ) --> 2009-1-lua