Lua Object-Orientation Simple Object Orientation


Example

Here's a basic example of how to do a very simple class system

Class = {}
local __instance = {__index=Class} -- Metatable for instances
function Class.new()
    local instance = {}
    setmetatable(instance, __instance)
    return instance
-- equivalent to: return setmetatable({}, __instance)
end

To add variables and/or methods, just add them to the class. Both can be overridden for every instance.

Class.x = 0
Class.y = 0
Class:getPosition()
    return {self.x, self.y}
end

And to create an instance of the class:

object = Class.new()

or

setmetatable(Class, {__call = Class.new}
    -- Allow the class itself to be called like a function
object = Class()

And to use it:

object.x = 20
-- This adds the variable x to the object without changing the x of
-- the class or any other instance. Now that the object has an x, it
-- will override the x that is inherited from the class
print(object.x)
-- This prints 20 as one would expect.
print(object.y)
-- Object has no member y, therefore the metatable redirects to the
-- class table, which has y=0; therefore this prints 0
object:getPosition() -- returns {20, 0}