This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
mrodin's profile picture

Loading randomly selected strings from a file

Started by mrodin, 19 March 2015 - 01:41 PM
mrodin #1
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!
Lyqyd #2
Posted 19 March 2015 - 03:10 PM
Split into new topic.

Please don't post questions on unrelated ancient threads.
AssossaGPB #3
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.
CrazedProgrammer #4
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
Bomb Bloke #5
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
CrazedProgrammer #6
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!
GopherAtl #7
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