Game Development Reference
In-Depth Information
Now we have a very simple 3D vector class! You can extend this class with more
metamethods for addition, multiplication, etc. Check out Assets/Scripts/PreInit.lua
in the Teapot Wars code base for the complete Vec3 listing, including a number of
these metamethods defined.
Incidentally, inheritance works exactly the same way. If you want Vec3 to inherit
from something, simply set up a metatable and point the __index field to the base
class. Lua doesn
'
t distinguish between classes and objects; they
'
re all just tables, which
may or may not have metatables.
It ' s worth noting that metatables are very similar to C++ virtual tables, which are the
tables used by C++ to store virtual functions. When you call a virtual function, C++
looks it up in the virtual table to find the actual implementation. Lua metatables with
the __index field behave much the same way. With all the other meta fields avail-
able to Lua, it makes the language itself extremely flexible.
Creating a Simple Class Abstraction
As you can see, with a little legwork, Lua fully supports object-oriented programming
techniques. There
'
s still one thing missing. The Vec3 class will work very well, but
it
s still not as easy as defining a class in C++, C#, Python, or any other truly
object-oriented language. Our ultimate goal is something like this:
'
class SomeClass : public BaseClass {};
What we really need is to abstract away all the metatable stuff into a function you
can call that generates the class table and allows you to instantiate objects from it.
function class(baseClass, body)
local ret = body or {};
-- if there
s a base class, attach our new class to it
if (baseClass
'
= nil) then
setmetatable(ret, ret);
ret.__index = baseClass;
end
˜
-- Add the Create() function
ret.Create = function(self, constructionData, originalSubClass)
local obj;
if (self.__index
= nil) then
if (originalSubClass
˜
= nil) then
obj = self.__index:Create(constructionData, originalSubClass);
else
obj = self.__index:Create(constructionData, self);
end
˜
 
 
Search WWH ::




Custom Search