Access_Denied's Forums

Site Resources => Tutorials => Topic started by: Access_Denied on June 14, 2007, 03:28:50 AM



Title: Tutorial Nine: File IO
Post by: Access_Denied on June 14, 2007, 03:28:50 AM
Hello, and welcome back to the next exciting tutorial. In this lesson, we'll be covering reading and writing files. Let's begin. Notes!

--Reading and Writing Files
--September 9, 2006

Next. Color variable.

orange = Color.new(255,128,0)

Now for our main loop:

while true do
screen:clear()

First we're going to be focusing on reading a file. So create a .txt file, or any other type of file, and write something in it. Something short, like "ProgramLua Rocks!" Now we're going to read it:

ourfile = io.open("test.txt","r")

Now the first part, is just the variable we've assigned to the file. The next part just tells the PSP that we're opening a file. Inside the parentheses, the first part is the name of the file, in quotes. The second part tells the PSP that we're opening the  text file in read mode, and not writing to it.

ourtext = ourfile:read()

This reads the first line of the file. To read the second line, do the same thing, except give it a different variable. Now let's close the file.

ourfile:close()

Now let's print the text we just read, to the screen.

screen:print(100,100,ourtext,orange)

Now end the program.

screen.waitVblankStart()
screen.flip()
end

Now if you run the program, it should print your text. Now, I'm going to show you a quick example of writing to a file. It won't be a working program, just an example.

ourfile = io.open("test","w")

You should know the first parts, but the "w" just means that you are writing to the file. Note, that putting a "w" there will overwrite the existing data. To make it add to the existing data use "a" instead of "w". Also, using "a" will write the data to the same line, to make it skip a line, do something like,"\nHello".
Now, back to the example.

ourline = "I'm writing files"
ourfile:write(ourline)
ourfile:close()

Easy huh? Well, here's one more way to read a file.

dofile("Files/play.lua")

What this does, is runs another lua file. But also note, this lua file is in the sub directory, "Files". This is sort of like a funtion, only in a different lua file. There are two types of lua files to run. One with a main loop. This will be like another program. And one with variables. So if you had a whole lua file full of vaiables, soon as you ran that file, it would declare those variables. This is one of the harder tutorials that I've written. I hope you still learn from it though. See ya in the next tut!


Hosted by www.Geocities.ws

1