Scripting OOP: compare Lua and Javascript by examples

Lua ‘table’ and Javascript ‘object’ are very similar. For OO programming, Javascript is more convenient, as it has more supporting functions, which you should implement yourself for Lua.

Lua example

local seekmethod = function(...)
   local allclasses = {...}
   return function(t, method)
      for k, class in pairs(allclasses) do
         local f = class[method]
         if f then
            return f
         end
      end
   end
end

local Person = {}
Person.new = function(self)
   local m = {}
   m.canTalk = true
   return setmetatable(m, {__index = seekmethod(self)})
end

Person.greet = function(self)
   if self.canTalk then
      print('Hi, I am ' .. self.name)
   end
end

local a = Person:new()
a.name = 'joe'
a:greet()

local a1 = Person:new()
a1.name = 'bob'
a1:greet()

-- output joe again
a:greet()

local Baby = {}
Baby.new = function(self)
   local m =  Person:new()
   m.canTalk = false
   return setmetatable(m, {__index = seekmethod(self, Person)})
end

Baby.cry = function(self)
   print("Wa ....")
end

b = Baby:new()

b:greet() -- output nothing
b:cry()

Javascript example

var Person = function() {
    this.canTalk = true;
};

Person.prototype.greet = function() {
    if (this.canTalk) {
        console.log('Hi, I am ' + this.name);
    }
};

var a = new Person();
a.name = 'joe';
a.greet();

var a1 = new Person();
a1.name = 'bob';
a1.greet();

//output joe again
a.greet();

var Baby = function() {
    Person.call(this);
    this.canTalk = false
};
Baby.prototype = Object.create(Person.prototype);
Baby.prototype.cry = function() {
    console.log('Wa ....');
};

b = new Baby();
b.greet(); //output nothing
b.cry();