Lua入门
1 --函数 2 function splitStr(theString) 3 stringTable = {} 4 5 local i = 1 -- 局部变量 6 for word in string.gmatch(theString, "[^%s]+") do -- 用到了正则 7 stringTable[i] = word; 8 i = i + 1 9 end -- for ... do ... end 10 11 return stringTable, i 12 end 13 14 stringTable, numOfWord = splitStr("The Turtle Is A Dog ")-- 调用函数 15 16 for j = 1, numOfWord-1, 1 do 17 print(string.format("第 %d 个单词是 %s ", j, stringTable[j])); 18 end 19 20 -- 缺省参数函数 21 function getSumMore(...) 22 local sum = 0 23 for k, v in pairs {...} do 24 sum = sum + v 25 end 26 return sum 27 end 28 29 io.write("Sum ", getSumMore(1, 2, 3, 4, 5, 6), "\n") 30 31 --好用 32 double = function(x) return x*2 end 33 print(double(8)) 34 35 --协程 36 co = coroutine.create(function() 37 for i=0, 10, 1 do 38 print(i) 39 print(coroutine.status(co)) 40 if i == 5 then -- if ... then ... end 41 coroutine.yield() -- 协程挂起(让出资源) 42 end 43 end 44 end 45 ) 46 47 print(coroutine.status(co)) 48 49 coroutine.resume(co) 50 51 co2 = coroutine.create(function() -- 协程创建 52 for i = 100, 110, 2 do 53 print(i) 54 end 55 end) 56 57 coroutine.resume(co2) -- 唤醒(运行) 58 coroutine.resume(co) 59 60 --文件操作 61 file = io.open("test.lua", "w+") 62 file:write("This is the first line.\n") 63 file:write("This is the second line.\n") 64 65 --读一下文件,回到文件头部 66 file:seek("set", 0) 67 print(file:read("*a"))--后面的接上 68 69 file:close() 70 71 --继续使用 72 file = io.open("test.lua", "a+") 73 file:write("This is a extra line.\n") 74 file:seek("set", 0) 75 76 print(file:read("*a")) 77 78 file:close() 79 80 --OO伪造 81 Animal = { height=0, weight=0, name="No name", sound="No Sound" } 82 83 function Animal:new(height, weight, name, sound) 84 setmetatable ( {}, Animal) 85 86 self.height = height 87 self.weight = weight 88 self.name = name 89 self.sound = sound 90 91 return self 92 end 93 94 function Animal:toString() 95 animalStr = string.format("%s weight %.1f lbs, is %.1f in tall and says %s.", self.name, self.weight, self.height, self.sound) 96 return animalStr 97 end 98 99 yoci = Animal:new(10, 15, "yoci", "Woof") 100 101 print(yoci.name) 102 print(yoci.sound) 103 print(yoci:toString()) 104 105 cat = Animal:new(2, 22, "candy", "miao") 106 print(cat.sound)
优质入门资源👉 一个视频学会Lua