簡體   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