Basically, I am creating a ModuleScript to store questions and answers in different subjects. Here is an example:
local questions = {
["Math"] = {
["What is 9 + 10?"] = "19",
["What shape has 5 sides?"] = "pentagon",
["What is the perimeter of a circle called?"] = "circumference"
},
["Science"] = {
["What stage of the water cycle is rain/snow/hail?"] = "precipitation",
["What is the first element of the periodic table?"] = "hydrogen",
["How many bones are in the human body?"] = "206"
},
["English"] = {
["What figure of language compares 2 things using like or as?"] = "simile",
["What is the name of a word that describes an action? (ex. run, walk)"] = "verb",
["How many letters are in the English alphabet?"] = "26"
}
}
I used a ModuleScript for this because I want to have functions for the module, and one of them is getting the length of the dictionary, and this is it:
function questions.getSubjectAmount()
local subjectAmount = 0
for subject, questions in pairs(questions) do
subjectAmount += 1
end
return subjectAmount
end
However, since I’m also storing functions in the dictionary, it will count those too as a “subject”.
I don’t want this to happen, and I could just check whether every item in my dictionary isn’t a function, but this feels like a very wrong way to do it.
Is there a better way to store this without having to check whether or not every item in my dictionary is a function or not? Or is that the way to do it? I don’t have a lot of experience with ModuleScripts, btw.
Then I believe you have a design flaw. A table of data should only have data and nothing else. Consider isolating it and keep the functions in a separate table.
I suggest doing the things mentioned above; BUT, its still possible to do what you asked.
function questions.getSubjectAmount()
local subjectAmount = 0
for subject, questions in pairs(questions) do
-- EDIT*: Not sure how your table functions are structured. Could possibly be typeof(questions)
if typeof(subject) == "function" then
continue
end
subjectAmount += 1
end
return subjectAmount
end
I’m going to do what @Prototrode said and what @azqjanna by creating a separate metatable for my main questions table in the ModuleScript. After reading up on metatables for a while now, I’ll definitely be using them in the future!