Lua基础

--Table当Map使用
var={name="a",sex=1,age=18}

for key,var in pairs(var) do
  print(key,var)
end

--Table当数组使用
arr={1,1,2,3,"hello"}

table.insert(arr,1,"world")
print(table.maxn(arr))

for key,var in pairs(arr) do
  print(key,var)
end


--复制表的方式面向对象 
People={}

function People.sayHi()
  print("hi")
end

People.sayBey=function()
  print("bye")
end

function clone(tab)
  ins={}
  for key,var in pairs(tab) do
    ins[key]=var
  end
  return ins
end

function People.new(name)
  ins=clone(People)
  ins.name=name
  return ins
end

People.sayBey=function(self)
  print("bye"..self.name)
end


p=People.new("Hel")
p.sayHi()
print(p.name)

--下面两句等价
p.sayBey(p)
p:sayBey()



--复制表的方式继承
function copy(dist,tab)
  for key,var in pairs(tab) do
    dist[key]=var
  end
  return dist
end

Man={}
Man.new=function(name)
  local self=People.new(name)
  copy(self,Man)
  return self
end


Man.sayHello=function()
  print("Man sya hello")
end

local m=Man.new("Lisi")
m.sayHello()

m:sayBey()


--函数闭包的方式面向对象 
function People(name)
  local self={}

  local function init()
    self.name=name
  end

  self.sayHi=function()
    print("Hi")
  end

  init()
  return self
end

local p=People("gg")
p.sayHi()

--函数闭包的方式继承
function Man(name)
  local self=People(name)

  local function init()

  end

  self.sayMan=function()
    print("Man say"..self.name)
  end

  return self
end

local m=Man("g")
m.sayMan()
m.sayHi()

你可能感兴趣的:(lua基础)