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

Storing strings Boolean's etc...

Started by Hraponssi, 19 October 2015 - 09:52 AM
Hraponssi #1
Posted 19 October 2015 - 11:52 AM
how would i store things like a password or name etc?
example: i would have a directory and save the passwords usernames etc there… and then later on after a restart of the computer, i could load the password username and other data.
thanks in advance :D/>
KingofGamesYami #2
Posted 19 October 2015 - 01:38 PM
I'd store them in a table, then serialize the table and save it to a file. Username / Password example:


local users = {} --#create a table to store stuff in

local function addUser( name, pass ) --#adds a user to the table
  users[ name ] = pass
end

local function saveUsers() --#saves the users table to the "users" file
  local file = fs.open( "users", "w" )
  file.write( textutils.serialize( users ) )
  file.close()
end

local function loadUsers() --#loads the users table from the "users" file
  local file = fs.open( "users", "r" )
  users = textutils.unserialize( file.readAll() )
  file.close()
end

if fs.exists( "user" ) then --#if the file already exists, we want to load it
  loadUsers()
end

--# Other stuff here
Edited on 19 October 2015 - 11:39 AM
Hraponssi #3
Posted 19 October 2015 - 04:03 PM
I'd store them in a table, then serialize the table and save it to a file. Username / Password example:


local users = {} --#create a table to store stuff in

local function addUser( name, pass ) --#adds a user to the table
  users[ name ] = pass
end

local function saveUsers() --#saves the users table to the "users" file
  local file = fs.open( "users", "w" )
  file.write( textutils.serialize( users ) )
  file.close()
end

local function loadUsers() --#loads the users table from the "users" file
  local file = fs.open( "users", "r" )
  users = textutils.unserialize( file.readAll() )
  file.close()
end

if fs.exists( "user" ) then --#if the file already exists, we want to load it
  loadUsers()
end

--# Other stuff here

sorry but it doesnt work for me, can you give me instructions. i tried making a file called "users" etc but would get an error
KingofGamesYami #4
Posted 19 October 2015 - 05:02 PM
The program creates the file automatically, you can edit it though.

In your program, if you want to add a username / password combination, simply call

addUser( name, pass )

And when you want to save it (usually immediately after adding a user)

saveUsers()

The code I posted will automatically create the table "users", which can be accessed like this:

if users[ "hello" ] then --#checks if the user "hello" exists

end

if users[ "hello" ] == 123 then --#checks if the password for the user "hello" is 123

end