简体   繁体   中英

Higher order “methods” in lua

This code in lua will apply a function to a value

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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