2 posts
Posted 19 March 2015 - 02:41 PM
Writing a script for multiple choice questions, i have a questions.db file that holds the question. There are 10 plus in the quesitons.db file. I want to choose 5 random questions in random order. Any pointers? I'm an advid php programmer but new to lua.
thanks for the help in advance!
8543 posts
Posted 19 March 2015 - 03:10 PM
Split into new topic.
Please don't post questions on unrelated ancient threads.
132 posts
Location
Florida, USA
Posted 19 March 2015 - 03:30 PM
You can use the fs api to read individual lines into an table. Then select random indexes of that table, checking for duplicates.
546 posts
Location
Wageningen, The Netherlands
Posted 19 March 2015 - 04:03 PM
local file = fs.open("questions.db", "r")
local line = file:readLine()
local lines = { }
while line do
table.insert(lines, line)
line = file:readLine()
end
file:close()
local selectedLines = { }
while #selectedLines < 5 do
local index = math.random(#lines)
if lines[index] ~= "" then
table.insert(selectedLines, lines[index])
lines[index] = ""
end
end
You can use this piece of code to load 5 random questions (no duplicates) into the table selectedLines from the file questions.db (assuming the functions are put into seperate lines)
Edited on 19 March 2015 - 03:04 PM
7083 posts
Location
Tasmania (AU)
Posted 19 March 2015 - 11:38 PM
That should work, but just a tip, you could shrink this:
local line = file:readLine()
local lines = { }
while line do
table.insert(lines, line)
line = file:readLine()
end
… down to this:
local lines = { }
for line in file.readLine do table.insert(lines, line) end
546 posts
Location
Wageningen, The Netherlands
Posted 20 March 2015 - 07:30 AM
That should work, but just a tip, you could shrink this:
local line = file:readLine()
local lines = { }
while line do
table.insert(lines, line)
line = file:readLine()
end
… down to this:
local lines = { }
for line in file.readLine do table.insert(lines, line) end
Wow I didn't know you could do that, thanks!
871 posts
Posted 20 March 2015 - 07:34 AM
to use file:lines(), you have to use io.open instead of fs.open when opening the file. lines is a convenience added by the io wrapper, not present directly on the underlying fs file objects.
Just realised bombbloke didn't do file:lines(), he just did file.readline. Which probably works, now that I think about it. Huh. Disregard.
Edited on 20 March 2015 - 06:36 AM