[英]Higher order “methods” in lua
This code in lua will apply a function to a value lua中的这段代码会将一个函数应用于一个值
function Apply(f, value)
return f(value)
end
I can then use it like this apply arbitrary functions calls on my game object like so 然后,我可以像这样使用它,在我的游戏对象上应用任意函数调用,就像这样
Apply(Draw, GameObject)
Apply(Update, GameObject)
Is it possible to instead do what I would, probably incorrectly, call a higher order method 是否可以代替我可能会错误地调用高阶方法的方法
function GameObject:Apply(f)
return self:f()
end
What I eventually want to do is have a table of GameObjects, that I can call Methods on in batch. 我最终想要做的是有一个GameObjects表,我可以批量调用Methods。 So using this "higher order method" concept that may not even exist I would create code that does the following.
因此,使用甚至可能不存在的“高阶方法”概念,我将创建执行以下操作的代码。
...
--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)
You'll probably want to pass function NAME if you're dealing with methods on other objects, because methods with same name on different objects may resolve to very different functions. 如果要处理其他对象上的方法,则可能要传递函数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
function GameObject:Apply(f)
return f(self)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.