With the introduction of the function type() it is now possible to know the type of the variable.
So I tried to find a way to implement a simple class system and I think I found a way
First we need a function to copy tables
function copy(o)
local c
if type(o) == 'table' then
c = {}
for k, v in pairs(o) do
c[k] = copy(v)
end
else
c = o
end
return c
end
Then we can declare our objects the following way:
vec = {}
vec.x = 0
vec.y = 0
function vec:add(v)
self.x += v.x
self.y += v.y
end
function vec:subs(v)
self.x -= v.x
self.y -= v.y
end
function vec:mult(c)
self.x *= c
self.y *= c
end
To create multiple instances of vector, we just need to copy the object and edit it's attributes
a = copy(vec)
b = copy(vec)
a.x = 1
a.y = 2
b.x = 3
b.y = -1
And when we call the a:add(b)
we get a.x == 4, a.y == 1
What's more we can define "subclass"
vec3 = copy(vec)
vec3.z = 0
function vec3:printz()
print(self.z)
end
The function printz()
will run just fine on copies of vec3
but will return an error on copies of vec