Skip to content

Instantly share code, notes, and snippets.

@svanellewee
Created August 21, 2014 07:40
Show Gist options
  • Select an option

  • Save svanellewee/5c4fbec192f11129e90c to your computer and use it in GitHub Desktop.

Select an option

Save svanellewee/5c4fbec192f11129e90c to your computer and use it in GitHub Desktop.
So Lua supports prototypal OOP!
--[[
javascript:
function SomeObject(name) {
this.name = name
}
SomeObject.prototype.getName = function() {
return "My Name is "+this.name+"!";
}
var obj = new SomeObject(name);
console.log(obj.getName());
Object.create(X){ function G() {}; G.prototype = X; return new G(); }
]]
Object = {}
function Object.create(obj)
obj = obj or Object
local newobj = {}
setmetatable(newobj, { __index = obj } ) -- prototype setting?
return newobj
end
local bla = {}
bla.name="Robert"
function bla:getName()
return "My name is "..self.name ..", how do you do?";
end
print(bla:getName())
local bla2 = Object.create(bla);
bla2.name="Cecil"
bla2.surname = "Von Bla"
function bla2:getSurname()
return "My surname is "..self.surname.."..isnt that weird!?";
end
print(bla2:getName(), bla2:getSurname())
print(bla:getName())
local bla3 = Object.create(bla2)
bla3.name = "Charles"
bla3.surname = "Xavier"
print(bla2:getName(), bla2:getSurname())
print(bla3:getName(), bla3:getSurname())
print(bla:getName())
@svanellewee
Copy link
Author

note the use of colons vs dots (: --> adds self param)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment