Learning more about metatables

Hello,

I’ve created this post so I can develop my skills with metatables. I got a project in my mind and for that I need to know more about metatables.

Here’s what I mean:

There must be a string with a int so for example number 1 has the text “Welcome to this topic”
and number 2 has the text “Goodbye”.

And what I want to do with them is that each number contains information. Those numbers must be inside a metatable or something else. And those numbers inside the metatable have the text that belongs to that specific number.

So for example if I want to have hundreds of questions with their answers I theoretically need hndreds of metatables with strings that say the questions. And if I want to randomize it so the script will pick one question out and put the question in a textlabel, then the answers must be similar to the question.

So for example I need:

  • A metatable which is the question

  • Inside those metatables strings that say the answers and question.

  • Numbers attached to the answers and question so the script knows which one is the question and which ones are the answers. And the correct answer needs to be indicated as correct.

So if someone could show me an example and tell me what everything does that would be awesome!!

You want to know how/what metatables are, yes?

Metatables allow you to add special functions to tables, to make them more dynamic.

You can set a metatable to a table via setmetatable

Here is an example:

local myTable = {}
setmetatable(myTable, {__index = function(...) return "test" end})

print(myTable["anything"]) -- prints "test"

You can learn more about them here

Ok, but how do I attach answers for the question? Like this?

local Question = {}
setmetatable(Question, {__index = function(...) return "answer" end})

--here the code so it can put the question and answer in the textlabel

I’m not sure I understand what you mean.

Why do you need metatables for this at all? Can’t you just use regular tables?
i.e.

local Question = {
   id = 12345,
   content = "How do I do this?",
   answers = {
      {
         id = 6789,
         content = "By doing this: xyz"
      }
   }
}

So what you mean is that each question has its id, and that can be used to look up information about it?
So like this:

local Questions = {
   [123] = {
      content = "How many slices of pizza?",
      answers = {456, 789}
   }
}

local Answers = {
   [456] = {
      content = "5",
   },
   [789] = {
      content = "10! Even that's not enough!",
   }
}
1 Like

Exactly like that!!

This looks so simple and now I understand it, it is actually very simple.

Thanks for your help!