## A Question about Lua Metatable vs. Normal Table

All Gurus once were Newbies
Forum rules
There are no such things as "stupid" questions. However if you think your question is a bit stupid, then this is the right place for you to post it. Please stick to easy to-the-point questions that you feel people can answer fast. For long and complicated questions prefer the other forums within the support section.
sphyrth
Level 4
Posts: 333
Joined: Mon Jan 04, 2016 7:14 am

### A Question about Lua Metatable vs. Normal Table

Note:
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()
``````
Trying to learn Metatables, this is what it looks like:

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()
``````
Now for my question:
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?
I have a favorite game. It's on my Youtube Channel.