Skip to content

Instantly share code, notes, and snippets.

@icebreaker
Created September 19, 2010 17:11
Show Gist options
  • Save icebreaker/586941 to your computer and use it in GitHub Desktop.
Save icebreaker/586941 to your computer and use it in GitHub Desktop.
--[[
Simple Class Implementation for Lua using Metetables.
This is very clean and simple, sticking to some very
simple principles.
Static methods defined with . (dot) and instance methods
with : (semicolon) .
Default values declared when defining the initial table.
The .new static method implements the constructor which
sets the metatable and do other chores as necessary.
The metatable is self-contained and its index points to the
initial table.
--]]
Entity =
{
name="Default",
x=0,
y=0
};
Entity.metatable = { __index = Entity };
Entity.new = function(name)
local self = {}
setmetatable(self, Entity.metatable);
if name ~= nil then self:setName(name); end
return self;
end
function Entity:setName(name)
self.name = name;
end
function Entity:move(x,y)
self.x = x;
self.y = y;
end
function Entity:speak()
print(string.format("Hey, I am %s sitting over here %d, %d ...", self.name, self.x, self.y));
end
e = Entity.new('Orc');
e:move(10,10);
e:speak();
e2 = Entity.new('Player');
e2:move(15,10);
e2:speak();
e3 = Entity.new();
e3:speak();
e3:setName('Zombie');
e3:move(20,25);
e3:speak();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment