I don't know where to actually ask this, so I'm putting my trust on you guys to either
answer me directly, or to refer me to the proper forum/site to ask this.
For this example, I'm making a Shape 'class' in Lua that can instantiate a shape that will have
(1) a number of corners, and (2) a move function.
Implementing it the way I would normally do (with normal tables), this is what it looks like:
Code: Select all
shape = {}
function shape:new(corners)
local s = {}
s.corners = corners and corners or 3
function s:move()
-- Move the shape
end
return s
end
square = shape:new(4)
square.move()
Code: Select all
shape = {}
-- 1. Setting up Metatable
shape.mt = {}
shape.mt.__index = square.mt
-- 2. Giving Default Values
shape.mt.corners = 3
setmetatable(shape, shape.mt)
-- 3. Using __call as an Instantiation Function
function shape.mt:__call(corners)
local s = setmetatable({}, shape.mt)
s.corners = corners
return s
end
-- Some random function
function shape.mt:move()
-- Move the shape
end
-- Instantiating and using its function
square = shape(4)
square:move()
Since using Normal Tables looks simpler, should I just use Normal Tables for simple stuff these,
or should I keep using the Metatable Example just to get the hang of it?