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一日游:(3)面向对象——复制表形式

Published at发布于:: 2014-03-09   |   Reading阅读:: 2 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
-- 我们定义一个对象People(其实是一个表)
People = {}

-- 定义成员函数方式1
--function People.sayHi()
--	print("people say hi")
--end

-- 定义成员函数方式2(推荐),这是People对象中得成员方法
People.sayHi = function(self)
  print("People say hi:"..self.name)  --..表示字符串链接
end

-- 方法:克隆一个table, 用于利用现有对象创建新对象
function clone(tab)
  local ins = {} -- 这是一个local table
  for key, var in pairs(tab) do -- 将tab中得对象拷贝到ins中
    ins[key] = var
  end
  return ins -- 返回ins
end

-- 可以理解为一个构造函数
People.new = function (name)
  local self = clone(People) -- 通过现有对象来构造新对象
  self.name = name
  return self
end

--local p = clone(People) -- 类似与实例
--p.sayHi()

-- 使用new方法来构造一个新的对象p,并且调用了People对象的成员方法sayHi()
local p = People.new("zhangsan")
--p.sayHi(p) -- 这两种调用形式都可以,
p:sayHi()    -- 上下两行一样(推荐这种)

-- 实现继承
Man = {} -- 定义了一个Man对象

-- 方法:tab中得对象copy到dist中
function copy(dist, tab)
  for key, var in pairs(tab) do
    dist[key] = var
  end
end

Man.new = function(name)  --这是Man的构造方法
  local self = People.new(name) -- Man是从People中继承下来的
  copy(self, Man)-- man的所有实例需要附加到people
  return self
end

  -- 这是Man的成员方法
Man.sayHello = function()
	print("Man say hello:")
end

  -- 并且我们还可以重写People的sayHi()方法
Man.sayHi = function (self)
  print("Man sayHi"..self.name)
end

-- 例
local m = Man.new("changkun")
m:sayHello()
m:sayHi()
#Lua#
  • Author:作者: Changkun Ou
  • Link:链接: https://changkun.de/blog/posts/lua-3/
  • All articles in this blog are licensed under本博客所有文章均采用 CC BY-NC-ND 4.0 unless stating additionally.许可协议,除非另有声明。
Lua一日游:(4)面向对象——函数闭包形式
Lua一日游:(2)Table和Array

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%