Created
August 21, 2014 07:40
-
-
Save svanellewee/5c4fbec192f11129e90c to your computer and use it in GitHub Desktop.
So Lua supports prototypal OOP!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| --[[ | |
| 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()) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
note the use of colons vs dots (: --> adds self param)