Sometimes its useful to create generic interfaces and behaviors on objects that other objects can inspect to see if they can communicate and interact with each other.
For instance, let's say we have two types of MeshEntities, a box and a sphere, that each implement a function called 'react()':
Here's the BoxEntity's code:
function MeshEntity:react() self:getMeshModel():getShape().dimensions = self:getMeshModel():getShape().dimensions + vector3(0.5,0.5,0.5) end
And the SphereEntity's code:
function MeshEntity:react() self:getMeshModel():getShape().radius = self:getMeshModel():getShape().radius + 0.5 end
The point of 'react()' is each object does something different. The box grows its box dimensions while the sphere grows its radius each time its called.
Now let's say we have a Trigger that these objects can pass through. The Trigger can inspect the object that passes through, check to see it implements a 'react()' function and call that function if it has it:
function Trigger:onEnter(obj) -- Check to see if the object implements the react() function/behavior if (obj.react) then -- If it does, call the object's react() function obj:react() end end
This type of generic programming allows us to define functionality that other objects can inspect and handle accordingly without needing to know specific details of the other object aside from a set of predefined member/function names. By testing for their existence and only calling them if they exist, we can build robust interoperable objects.