Yeah, there are some modifications that could be done to make it more understandable. What I’d written allowed for a tad more flexibility. If your table’s keys started with Question
and ended with a number, you could do…
local QuestionsTable = {
Question1={
1,
"rwaer",
50
},
Question2={
41,
"cool",
"nice"
}
}
local question = QuestionsTable["Question" .. math.random(1, 2)]
The only issue with this is that:
- The number of questions are hard-coded in
math.random
, and - If key
Question
was misspelled or didn’t have consistent capitalization, it wouldn’t throw an error.
The solution I gave prior would be the best way to go about it. Here’s something slightly more modified to make it more readable.
local QuestionsTable = {
Question1={
1,
"rwaer",
50
},
Question2={
41,
"cool",
"nice"
}
}
local TotalQuestions = 0 -- Since dictionaries do not have numbered indices, we have to keep track of the number of questions manually.
for _ in next, QuestionsTable do
TotalQuestions = TotalQuestions + 1 -- Increments the TotalQuestions 1 by, later used for math.random.
end
local function GetQuestion(num)
local QuestionInfo = nil -- No question found yet
for Question, Data in pairs(QuestionsTable) do
local temp = string.lower(string.sub(Question, 1, 8)) -- string.lower lowercases all letters, removing case-sensitivity. string.sub returns the letters between positions A and B.
if temp == "question" then
local qnum = tonumber(string.sub(Question, 9)) -- tonumber converts a string to a number (if applicable). string.sub returns every letter after the C position in the string.
if qnum ~= nil and qnum == num then -- Does Question<X> match what we want?
QuestionInfo = Data -- Set QuestionInfo to the question's data
break
end
end
end
return QuestionInfo -- Return the data
end
local RandomQuestionNum = math.random(1, TotalQuestions) -- Get a random number between 1 and the total number of questions in the table.
local QuestionToPresent = GetQuestion(RandomQuestionNum) -- Attempt to get the question with desired number.
if QuestionToPresent ~= nil then -- Did it manage to find the question?
print(QuestionToPresent)
-- code
end
Lmk if you have any further questions