Skip to content

Instantly share code, notes, and snippets.

@evilstreak
Last active March 29, 2016 22:55
Show Gist options
  • Save evilstreak/5523863 to your computer and use it in GitHub Desktop.
Save evilstreak/5523863 to your computer and use it in GitHub Desktop.
Playing with simple prototypal inheritance in Lua
Object = {};
function Object:clone( o )
return setmetatable( o, { __index = self } );
end
function Object:instanceOf( parent )
local mt = getmetatable( self );
if mt == nil or mt.__index == nil then
return false;
elseif mt.__index == parent then
return true;
else
return mt.__index:instanceOf( parent );
end
end
Person = Object:clone{ species = "human", hobbies = {} };
dom = Person:clone{};
alfie = dom:clone{};
-- working with primitives and assignment is simple
print( dom.name ); -- nil
print( alfie.name ); -- nil
dom.name = "Dom";
print( dom.name ); -- Dom
print( alfie.name ); -- Dom
alfie.name = "Alfie";
print( dom.name ); -- Dom
print( alfie.name ); -- Alfie
-- working with objects and mutation has some hazards
table.insert( dom.hobbies, "Geeking" );
print( unpack( dom.hobbies ) ); -- Geeking
print( unpack( alfie.hobbies ) ); -- Geeking
table.insert( alfie.hobbies, "Drooling" );
print( unpack( dom.hobbies ) ); -- Geeking Drooling
print( unpack( alfie.hobbies ) ); -- Geeking Drooling
Person.hobbies = {};
print( unpack( dom.hobbies ) ); -- <empty line>
print( unpack( alfie.hobbies ) ); -- <empty line>
-- instead, let's use a custom method to insert a hobby
function Person:addHobby( hobby )
local hobbies = rawget( self, "hobbies" );
-- incredibly naive shallow copy. good enough here
if hobbies == nil then
local hobbies = {};
for k, v in pairs( self.hobbies ) do
hobbies[ k ] = v;
end
self.hobbies = hobbies;
end
table.insert( self.hobbies, hobby );
end
dom:addHobby( "Geeking" );
print( unpack( dom.hobbies ) ); -- Geeking
print( unpack( alfie.hobbies ) ); -- Geeking
alfie:addHobby( "Drooling" );
print( unpack( dom.hobbies ) ); -- Geeking
print( unpack( alfie.hobbies ) ); -- Geeking Drooling
dom:addHobby( "Cycling" );
print( unpack( dom.hobbies ) ); -- Geeking Cycling
print( unpack( alfie.hobbies ) ); -- Geeking Drooling
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment