leonardchaocc / Application

0 stars 0 forks source link

LUA 速成 #6

Open leonardchaocc opened 4 years ago

leonardchaocc commented 4 years ago

LUA是动态的脚本语言 定义变量:变量名 = XXX;局部时在前面加关键字local --为注释 定义方法: function XXX() BBB end if语句: if XXX then BBB else CCC end 循环语句: for var=1, 100 do BBB end

table表:{} key-value式存储 e.g.: config= {}或config = {hello="hello lu", word = "word"} config.words = "hello" config.num = 100 config["names"] = "zhangsan" print(config["words"]) print(config.names) table的遍历: for key, var in pairs(config) do print(key,var) end

数组:以table的形式呈现(初始化不需要给key)数组索引从1开始 arr = {1,2,3,"hello"} for key,var in pairs(arr) do print(key,var) end

arr = {} for var=1, 100 do table.insert(arr,1,var) end print(table, maxn(arr)) for key, var in pairs(arr) do print(key,var) end

面向对象-复制表的方式 function clone(tab) local ins = {} for kdy, var in pairs(tab) do ins[key] = var end return ins end

function copy(dist,tab) --继承 for key,var in pairs(tab) do dist[key] = var end end

people = {} people.sayhi = function() --对象功能的两种声明方式 print("people say hi") end --function people.sayhi() print("people say hi") end people.new = function(name) --构造函数 local self = clone(people) self.name = name return self end

local p = clone(people) p.sayhi()

--local p = people.new("zhangsa") p:sayhi()

man = {} man.new = function (name) local self = people.new(name) copy(self,man) return self end man.sayhello = function() print("man say hello") end

man.sayhi = function(self) --函数的重写 print("man sayhi".. self.name) end

local m = man.new("LISI") m:sayhi()

函数闭包的方式实现面向对象 function people(name) local self = {} local function init() self.name = name end self.sayhi = function() print("hello" ..self.name) end init() return self end local p = people("zhangsan") p:sayhi

function main(name) --继承 local self = people(name) local function init() end self.sayhello = function() print("hi".. self.name) end return self end local m = man("list") --m.sayhello() m:sayhi()