object oriented programming
// OOP is a programming paradigm found in many languages today.
// Generally, an object is an instance of a Class.
// Here's a Java example:
public class Car
{
private double speed;
public Car(double initialSpeed) // Constructor, most common way to initialize objects of a class.
{
speed = initialSpeed;
}
// Accessor methods, aka getters
public double getSpeed()
{
return speed;
// This is an example of encapsulation, where
// methods are used to hide the implementation details
// and ensure the programmer can't modify things they shouldn't be able to.
}
public void accelerate()
{
speed++;
}
public void slowDown()
{
speed--;
}
}
-- look up for `k' in list of tables `plist'
local function search (k, plist)
for i=1, table.getn(plist) do
local v = plist[i][k] -- try `i'-th superclass
if v then return v end
end
end
function createClass (...)
local c = {} -- new class
-- class will search for each method in the list of its
-- parents (`arg' is the list of parents)
setmetatable(c, {__index = function (t, k)
return search(k, arg)
end})
-- prepare `c' to be the metatable of its instances
c.__index = c
-- define a new constructor for this new class
function c:new (o)
o = o or {}
setmetatable(o, c)
return o
end
-- return new class
return c
end