gpt4 book ai didi

oop - 使用什么作为元表?

转载 作者:行者123 更新时间:2023-12-04 15:10:48 24 4
gpt4 key购买 nike

阅读 http://lua-users.org/wiki/LuaClassesWithMetatable Vector 示例对元表使用以下技术:

Vector={}
Vector_mt={__index=Vector}

function Vector:new(x,y)
return setmetatable({x=x,y=y},Vector_mt)
end

function Vector:add(v)
return Vector:new(self.x+v.x,self.y+v.y)
end

假设我们要使用__add 来支持+ 运算符,我们需要在元表中明确提及它,还需要重新排序,以便在 Vector:add:

之后提到了 metatable 和构造函数
Vector={}

function Vector:add(v)
return Vector:new(self.x+v.x,self.y+v.y)
end

Vector_mt={__index=Vector,__add=Vector.add}

function Vector:new(x,y)
return setmetatable({x=x,y=y},Vector_mt)
end

为了避免在元表中提及每个元方法,我可以将 Vector 本身设置为元表,然后我可以添加 __add(另外,很明显, __index) 作为 Vector 的方法:

Vector={}

function Vector:new(x,y)
return setmetatable({x=x,y=y},Vector)
end

function Vector:add(v)
return Vector:new(self.x+v.x,self.y+v.y)
end

function Vector:__index(k)
return Vector[k]
end

function Vector:__add(b)
return self:add(b)
end

不推荐后者,为什么?

最佳答案

and also we need to reorder things, so that the metatable and the constructor are mentioned after Vector:add

没有。一张表就是引用。添加元表时,它不会被深度复制。您可以稍后向其中添加字段,它会影响元表。

这太复杂了:

function Vector:__index(k)
return Vector[k]
end

只需这样做:

Vector.__index = Vector

参见 https://codereview.stackexchange.com/a/253022/230923一个 Lua“类”的例子。

关于oop - 使用什么作为元表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65243035/

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