Lua: Basic Engine
Lua |
---|
Basics |
Intermediate |
Advanced |
|
XLua |
Add to this template |
This page covers the creation of a simple object engine. It will use many of the concepts from the other tutorials, so it is a good idea to read those first. For simplicity it assumes you are using MMF2 and a recent version of the XLua extension already set up and ready to go.
To start off, we need a way to store and create new object instances. We also want to define a few namespaces, which will be used to hold many functions and variables under one table; this is considered good practice and also makes some things easier. For instance, accessing object methods would be a mess if they were stored in the global namespace.
-- (NAMESPACES)
-----
object = { } -- object methods
-----
newid = 0 -- next id to assign object
instances = { }
object.getId = function ()
newid = newid + 1
return newid
end
object.new = function (data_table)
local var = data_table
local obj = {
__index = object, -- use the 'object' method table
id = object.getId(),
x = var.x or 0, -- default to 0 if no 'x' is supplied
y = var.y or 0,
}
setmetatable(obj, obj)
return obj
end
Though we really don't need the object to serve as its own metatable (we could move the __index metamethod to object and reflect that change in setmetatable), it helps keep the method table uncluttered and also gives the object a sort of "type" specification: it's obvious we know that this is an 'object' instead of something like 'hud_element', which would use an entirely different method set.
You'll also notice how that function expects a table of named elements instead of separate parameters; it doesn't matter which of those you go for, but for constructor functions like this it makes sense to use a table, since they're used exactly like a regular table construction anyway.
to be continued