Alright, this is how it works:
What it does
It will iterate through the number of questions, and select a random number between 1 and the Number of Questions.
This will error, because data is going to be removed. So lets say you take question 1 as the first question, and then question 6 as the second. Because you removed a value from the table it will error, since the table doesn’t have 6 indexes anymore after the first iteration. So set the for loop as for i=1, NumberOfQuestions do
, and have the math.random statement set to math.random(1,NumberOfQuestions+1-i)
.
After it stores the data from your randomly given index, it will unpack the data into the appropriate local variables. Then it will remove this question from the table. But this will error because the table name is questions, not question.
Then after the loop is done, local percent will be set to 0, since nothing incremented the variable numberCorrect.
What this means
Your script has no context, it parses data but does not do anything with that data. Since you’re parsing the data randomly, you should create the UI objects within each iteration or at least position them based off the iteration.
You must also create connections with events and the UI buttons.
Finally, you need to create a connection with a submit button and input event. Because the correct score will be loaded immediately after the questions are loaded.
Approach
local questions = {
{"Red",{"Red","Orange","Yellow","Green","Blue","Purple"},1}
{"Orange",{"Red","Orange","Yellow","Green","Blue","Purple"},2}
{"Yellow",{"Red","Orange","Yellow","Green","Blue","Purple"},3}
{"Green",{"Red","Orange","Yellow","Green","Blue","Purple"},4}
{"Blue",{"Red","Orange","Yellow","Green","Blue","Purple"},5}
{"Purple",{"Red","Orange","Yellow","Green","Blue","Purple"},6}
}
local answers={}
local numberCorrect = 0
local NumberOfQuestions = 6
for i = 1,NumberOfQuestions do
local TempQuestionNumber = math.random(1,NumberOfQuestions+1-i)
local QuestionData = questions[TempQuestionNumber]
local Question, Answers, CorrectAnswer = unpack(QuestionData)
table.remove(questions,TempQuestionNumber)
-- Iterate through all UI buttons for question TempQuestionNumber and connect them to the context; change method of iteration (This will not work in your current UI context)
for buttonNumber, button in <all buttons> do
button.MouseButton1Click:Connect(function () -- Will run when a button is clicked
answers[TempQuestionNumber]= (buttonNumber==CorrectAnswer) -- If this button is the correct one, store a true value in answers at position TempQuestionNumber
end)
end
end
someSubmitButton.MouseButton1Click:Connect(function ()
-- Increment correct Answers
for i=1,answer in pairs(answers) do
if answer==true then
numberCorrect=numberCorrect+1
end
end
local percentCorrect = math.floor(numberCorrect/NumberOfQuestion * 100)
-- Then do something with this variable; display it
end)