A Question about Lua Metatable vs. Normal Table

Quick to answer questions about finding your way around Linux Mint as a new user.
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. Stick to easy to-the-point questions that you feel people can answer fast. For long and complicated questions use the other forums in the support section.
Before you post read how to get help. Topics in this forum are automatically closed 6 months after creation.
Locked
sphyrth

A Question about Lua Metatable vs. Normal Table

Post by sphyrth »

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?
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 1 time in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
Locked

Return to “Beginner Questions”