How to Remember a Name

In this tutorial you will learn how to ask for a user's name and remember it when the user runs the script again.

Enter the IO library
To even ask for a string to be inputted by the user we need to use a new library, the io library.

The io library has a function called io.read which can be called to prompt the user to type in a string at runtime.

The script above asks for your name and then prints it to the output window.

Wait! It still forgets my name every time I run it!
Well, io.read is simply a function that allows you to get user input. To actually remember a name after the script ends you need to write a file to the disk then read it when the script starts.

You can do this using the io.open function. io.open must be called with at least the string argument path. This will attempt to open the file at the path in read mode. To open it in write mode you call it with a second argument mode which should be equal to "w" as you are opening it in write mode.

The function if it succeeds returns a special object called a file handle. To obtain the object you must call the function like this:

Now that you have the FileHandle you can use it like an object. In read mode the object has the read and close functions, while in write mode the object has the write, flush, and close functions.

The functions do what the names suggest they would. The read function reads a line from the file and returns the line, and the write function will append the write buffer with the string argument. The flush function will overwrite the file on the hard drive with the contents of the buffer, and the close function automatically flushes changed and closes the file handle.

Now you may quickly rush to test this for yourself and come up with a script like this thinking it will work. However if the script below is run it will throw an error and not finish.

The first problem with the script above is that the io.read function will return nil and a string if there was an error opening it, such as the file or the parent folder not existing. The script attempts to index the read function of the variable which will throw an error if the function has returned nil.

To prevent errors from using nil values you check if the file handle is not nil using an If Then End statement.

However this script is not actually fixed, as if the file handle exists the script will still error with a strange error message of "Script.lua:3: bad argument #1 to 'read' (FILE* expected, got no value)."

A File* is the internal name of a File handle in Lua, so this error is easily fixed by adding the File handle as an argument to both functions.

There we go, the script is fixed.

Write to the file
Now we need to add code to the script that asks for the user's name. It should be a trivial task to make it actually write the name to the file, simply copy and paste the file reading code and turn the line with  to.

Success! Now run your working code.