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 表,我可以在其中批量调用方法。因此,使用这个“更高阶方法”概念(可能并不存在),我会创建以下代码:

...
-- 带有三个子弹的批次游戏对象
BatchGameObjects = BatchGameObject:new(Bullet1, Bullet2, Bullet3)

--调用等效于
--Bullet1:DrawMethod()
--Bullet2:DrawMethod()
--Bullet3:DrawMethod()

--Bullet1:UpdateMethod()
--Bullet2:UpdateMethod()
--Bullet3:UpdateMethod()

BatchGameObjects:Apply(DrawMethod)
BatchGameObjects:Apply(UpdateMethod)
点赞
用户204011
用户204011
### 函数

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

```

说明: 该函数将 self 作为参数传入函数 f 中并将结果返回。GameObject 是其成员函数。

2014-09-28 19:20:27
用户936986
用户936986

如果你在处理其他对象的方法时,可能希望传递函数名称,因为不同对象上具有相同名称的方法可能解析为非常不同的函数。

function BatchGameObjects:Apply(function_name)
   -- ... 或以与存储方式匹配的任何其他方式迭代对象 ...
   for idx = 1, #self.object_list do
      local object = self.object_list[idx]
      object[function_name](object)
   end
end
2014-09-28 22:27:58