2014-09-28 48 views
2

此代碼在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) 

回答

3

你可能想通過函數名,如果你正在處理的其他對象的方法,因爲不同的對象有同名的方法可以解決非常不同的功能。

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 
+0

謝謝,這工作很好。其他人使用它的一個潛在問題是,當你使用你想要將它作爲字符串傳遞給它的函數時。 IE BatchGameObjects:應用(「繪製」)。謝謝!!! – user514156 2014-09-28 23:40:39

+0

@ user514156,是的,這就是我的意思,當我移情「名稱」。 – 2014-09-29 11:10:02

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