【发布时间】:2021-04-13 09:37:36
【问题描述】:
我正在阅读https://www.lua.org/pil/16.html上“Lua 编程”中的“面向对象编程”一章。
在那个例子中,他们创建了这个“构造函数”:
Account = {balance = 0}
function Account:new (o)
o = o or {} -- create object if user does not provide one
setmetatable(o, self)
self.__index = self
return o
end
我在 Linux 上用一个简单的time 在一个包含 1000 万个操作的脚本中进行了一些“sintetic 基准测试”。在表初始化之外定义Account.__index = Account 快了200ms。
我的问题是,如果我们可以在外部定义并执行一次,为什么要在这个函数内部设置每次调用这个函数时都会执行的self.__index?也许是遗产?
已编辑:
谢谢luther的回答,我这里只是给大家举个例子给大家看看:
local a = {}
a.__index = a
function a:foo()
return 'foo'
end
function a:new(o)
print(self)
o = o or {}
setmetatable(o, self)
-- self.__index = self
return o
end
local b = a:new()
-- b.__index = b
function b:bar()
return 'bar'
end
local z = a:new()
print(z:foo()) -- this will work
local y = b:new()
print(y:foo()) -- attempt to call method 'foo' (a nil value)
print(y:bar()) -- attempt to call method 'bar' (a nil value)
当然y 会有一个元表,b 作为那个表,但是b 没有__index 条目,这个条目只在b 的元表中。
如果您仍想避免在“构造函数”中声明 __index,则需要在每个派生原型或“子类”中指定它。
【问题讨论】:
-
你似乎是对的:
Account.__index = Account更好。 -
支持子类化
Account,如下章所示。 -
是的,我读过,但我仍然可以定义“子类”并在
new函数之外编写相同的SubAccount.__index = SubAccount并得到相同的行为。 -
如果
new方法分配__index,它将为每个子对象完成,而无需手动执行。
标签: lua