繁体   English   中英

lua中的高阶“方法”

[英]Higher order “methods” in lua

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

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

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

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

是否可以代替我可能会错误地调用高阶方法的方法

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

我最终想要做的是有一个GameObjects表,我可以批量调用Methods。 因此,使用甚至可能不存在的“高阶方法”概念,我将创建执行以下操作的代码。

...
--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
function GameObject:Apply(f)
    return f(self)
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM