2

Lua一日游:(4)面向对象——函数闭包形式

 2 years ago
source link: https://changkun.de/blog/posts/lua-4/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Lua一日游:(4)面向对象——函数闭包形式

Published at:

2014-03-09

  |  

Reading: 195 words ~1min

  |  

PV/UV: 3/3

我们直接来看代码:

-- 函数闭包来实现面向对象

  -- 运行速度略慢与复制表的方式, 不过可以忽略不计
function Car(name)
  local self = {} -- 函数内部的一个local value
  local function init()
    self.name = name
  end
  self.introCar = function()
    print("hello "..self.name)
  end
  init()
  return self
end

  -- 构造了一个Car对象
local p = Car("bengchi")
p:introCar()

  -- 继承的实现,如果我们假设Plane可以继承自Car的话
function Plane(name)
  local self = Car(name)

-- local function init() --也可以复写
-- end

  self.introPlane = function()
    print("hi "..self.name)
  end

  return self
end

local m = Plane("feiji")
m:introCar();
m:introPlane();

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK