gpt4 book ai didi

lua - 在 Lua 类中使用 self 关键字

转载 作者:行者123 更新时间:2023-12-04 19:46:30 32 4
gpt4 key购买 nike

我知道 Lua 中的“self”类似于 Java 中的“this”。 “this”表示Java中的当前对象,但我知道Java是面向对象的,而Lua是基于原型(prototype)的。谁能解释为什么下面的代码必须使用“self.last”而不是“self”来访问链表的当前节点?谢谢你。 :)

list = {}
list.__index = list

setmetatable(list, { __call = function(_, ...)
local t = setmetatable({length = 0}, list)
for _, v in ipairs{...} do t:push(v) end
return t
end })

function list:push(t)
if self.last then
self.last._next = t
t._prev = self.last
self.last = t
else
self.first = t
self.last = t
end
self.length = self.length + 1
end

最佳答案

您的程序中有两种不同类型的对象:列表对象和节点。列表对象管理链接节点链并具有以下字段:

listobject = {
length = 0, -- number of nodes managed by this list object
first = nil, -- reference to first node in this list; nil if list is empty
last = nil -- reference to last node in this list; nil if list is empty
}

对第一个节点的引用对于迭代和添加到列表非常有用,而 last 引用允许高效追加。 List 对象也有一个元表,这样你就可以调用它们的方法:

listobject:push( {"node1"} )

除非你做一些有趣的事情,否则 push 方法的 self 参数将始终是一个列表对象,而不是一个节点。

另一方面,节点引用链中的下一个和上一个节点:

node = {
_next = nil, -- might be nil if not in list or last node
_prev = nil, -- might be nil if not in list or first node
-- plus some data
}

因此在 push 方法中,您访问 self.last 以检查列表是否为空(您可以检查 self.length 作为好吧),如果不是,则在当前列表中找到最后一个节点,您可以在其中附加作为参数传递给 push 的新节点。当您这样做时,列表对象中的 last(和 first)引用显然必须更新。列表对象(push 方法主体中的 self)不是节点链的一部分。

关于lua - 在 Lua 类中使用 self 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27667629/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com