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

Need quick help again!

Started by rahph, 28 March 2015 - 01:08 PM
rahph #1
Posted 28 March 2015 - 02:08 PM
Hello. So i am writing mailing system, and i want it to register users via id's of pcs. DO not complain about security of it. it is just a test. So, when user registers his id, i have usrlist file. And i want to search for his id in this file. Is it possible? I might use checking amount of lines (1 id per line) and use for loop to check, BUT HOW TO DO IT (i mean get amount of lines.)

BTW: my lua knowlege is 1/10
Lignum #2
Posted 28 March 2015 - 03:43 PM
Read the file line by line and insert each line into a table. Then you can check whether the id is in the table.

local function tableContains(tbl, value)
   for _,v in pairs(tbl) do
	  if v == value then return true end
   end
   return false
end

local file = fs.open("myfile", "r")
local tbl = {}
for line in file.readLine do --# Iterate over each line in the file.
   table.insert(tbl, tonumber(line)) --# tonumber converts the line to a number.
end

print(tableContains(tbl, 5)) --# Prints true if the file contains the ID 5.

Keep in mind that you have to re-read the file every time it changes. So I suggest you load the file at the beginning of your program and modify the table instead of the file. Then, at the end of your program you save the modified table to the file.
ItsRodrick #3
Posted 28 March 2015 - 03:49 PM
I would save the file something like this:
{
"username1" = 6,
"anotherUser" = 85,
}

then, to read:

local usersFile = fs.open(path,"r")
local users = usersFile.readAll()
usersFile.close()

--Let's say I want to get id of user "anotherUser":
user = "anotherUser"
-- check for every key and value in a table
for key,value in pairs(users) do
  --if the var inside table users is equals the value of user, then return id
  if key == user then return value end
end