gpt4 book ai didi

class - lua中的高阶 "methods"

转载 作者:行者123 更新时间:2023-12-01 19:04:51 26 4
gpt4 key购买 nike

lua 中的这段代码将把一个函数应用于一个值

function Apply(f, value)
return f(value)
end

然后我可以像这样在我的游戏对象上应用任意函数调用来使用它

Apply(Draw, GameObject)
Apply(Update, GameObject)

是否可以做我会做的事情,可能是错误的,调用更高阶的方法

function GameObject:Apply(f)
return self:f()
end

我最终想要做的是拥有一个游戏对象表,我可以在其中批量调用方法。因此,使用这个可能根本不存在的“高阶方法”概念,我将创建执行以下操作的代码。

...
--Create the batch object with three bullets in it
BatchGameObjects = BatchGameObject:new(Bullet1, Bullet2, Bullet3)


--Call equivelent to
--Bullet1:DrawMethod()
--Bullet2:DrawMethod()
--Bullet3:DrawMethod()

--Bullet1:UpdateMethod()
--Bullet2:UpdateMethod()
--Bullet3:UpdateMethod()

BatchGameObjects:Apply(DrawMethod)
BatchGameObjects:Apply(UpdateMethod)

最佳答案

如果您正在处理其他对象上的方法,您可能需要传递函数 NAME,因为不同对象上具有相同名称的方法可能会解析为截然不同的函数。

function BatchGameObjects:Apply(function_name)
-- ... or iterate on objects in any other way that matches how you store them ...
for idx = 1, #self.object_list do
local object = self.object_list[idx]
object[function_name](object)
end
end

关于class - lua中的高阶 "methods",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26088579/

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