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

Searching Files

Started by asparagus, 20 November 2015 - 03:45 AM
asparagus #1
Posted 20 November 2015 - 04:45 AM
I have a file that is full of usernames and I want to be able to search that file for existing users and be able to add users to that file without their being any duplicates/spaces. Currently I'm using this doctored bit of code to search the file system but I'm having a problem adding other usernames using this system. Any help is appreciated.

name = "playername"
if fs.exists("users") then
   local file = fs.open("users", "r")
   local content = {}
   for line in file.readLine do
	  if line:find(name) then
		   print("Player Has Been Found.")
	  end
   end
   file.close()
end
I figured doing this would work, but I'm having no luck.

name = "playername"
if fs.exists("users") then
   local file = fs.open("users", "r")
   local content = {}
   for line in file.readLine do
	  if line:find(name) then
		   print("Player Has Been Found.")
  else
  local file = fs.open("users", "a")
  file.writeLine(name)
  file.close()
	  end
	  end
   file.close()
end
Bomb Bloke #2
Posted 20 November 2015 - 05:42 AM
You'd need to search the whole file before making the decision whether or not to add the user.

Eg:

local name, found = "playername", false

if fs.exists("users") then
	for line in io.lines("users") do
		if line:find(name) then
			print("Player Has Been Found.")
			found = true
		end
	end
end

if not found then
	local file = fs.open("users", "a")
	file.writeLine(name)
	file.close()
end
asparagus #3
Posted 20 November 2015 - 05:53 AM
Ahh, that makes a whole lot more sense now. Thank you.