Changkun's Blog欧长坤的博客

Science and art, life in between.科学与艺术,生活在其间。

  • Home首页
  • Ideas想法
  • Posts文章
  • Tags标签
  • Bio关于
  • TOC目录
  • Overview概览
Changkun Ou

Changkun Ou

Human-AI interaction researcher, engineer, and writer.人机交互研究者、工程师、写作者。

Bridging HCI, AI, and systems programming. Building intelligent human-in-the-loop optimization systems. Informed by psychology, sociology, cognitive science, and philosophy.连接人机交互、AI 与系统编程。构建智能的人在环优化系统。融合心理学、社会学、认知科学与哲学。

Science and art, life in between.科学与艺术,生活在其间。

276 Blogs博客
165 Tags标签
Changkun's Blog欧长坤的博客

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

Published at发布于:: 2014-03-09   |   Reading阅读:: 1 min   |   PV/UV: /

我们直接来看代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
-- 函数闭包来实现面向对象

  -- 运行速度略慢与复制表的方式, 不过可以忽略不计
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();
#Lua#
  • Author:作者: Changkun Ou
  • Link:链接: https://changkun.de/blog/posts/lua-4/
  • All articles in this blog are licensed under本博客所有文章均采用 CC BY-NC-ND 4.0 unless stating additionally.许可协议,除非另有声明。
Lua一日游:(5) cocos2dx 与 Lua
Lua一日游:(3)面向对象——复制表形式

Have thoughts on this?有想法?

I'd love to hear from you — questions, corrections, disagreements, or anything else.欢迎来信交流——问题、勘误、不同看法,或任何想说的。

hi@changkun.de
© 2008 - 2026 Changkun Ou. All rights reserved.保留所有权利。 | PV/UV: /
0%