Page 1 of 1

Introduction to Lua - Part IV Standard and File I/O

#1 KYA   User is offline

  • Wubba lubba dub dub!
  • member icon

Reputation: 3204
  • View blog
  • Posts: 19,238
  • Joined: 14-September 07

Posted 17 August 2009 - 09:20 AM

Introduction to Lua - Part IV

First, I'd like to acknowledge the enormous time gap between part three and this edition. It's hard to get something done when time is limited and then apathy hits. On top of that, the debate on what exactly to include before moving onto an "Advanced Lua" series was difficult to say the least. After much deliberation, I have decided to devote this final "intro" tutorial to I/O, both standard and of files since it is technically a beginner type topic and will be utilized in some of the Advanced Lua tutorials I plan on writing in the coming week. Having that said, let's get started:

This tutorial assumes you have a basic understanding of Lua, have it successfully installed on your system, and can run programs. A basic understanding of programming concepts is nice to have as well, but it isn't a deal breaker. If you haven't read any of the last three "Intro to Lua" tutorials you can find them here: Part I, Part II, Part III.

Lua contains two I/O models. They are aptly named the Simple Model and the Complete model. Up until this point we have used the simple model, for its "simplicity". Simple, no? From Roberto Ierusalimschy's book Programming in Lua (first edition is available online for free, covers up to Lua 5.0):


The simple model does all of its operations on two current files. The library initializes the current input file as the process standard input (stdin) and the current output file as the process standard output(stdout).

The above is a fancy way of saying "console" input and output. This information is the user (or a program) interacting with the basic I/O of the system. This is the same type of stuff you see in other programming languages' beginning type of programs. In short it is the equivalent of C's printf(), Java's System.out.println(), so on and so forth. Example:
--Basic output example
print("Hello World!")
io.write("Hello World!\n")

Both are examples of how to send text/data to the standard output, but one takes a more formatted approach then the other. At this point it is ultimately irrelevant which one you choose. Just note that print doesn't require a newline character appended to it.Input is similar and just as easy:

--Basic input:
print("Enter a string")	 -->prompt
data =			-->readin the whole line
io.write(data.."\n")		-->display back to the user

An example of the output to expect:


Hello World!
Hello World!

Enter a string
My name is Knowles
My name is Knowles

NOTE: If you type something, but then backspace due to a typo or whatever, io will still pick up on the key presses and display everything you typed.

Those are the basic "barebones" of the simple I/O model. There are many variations of how one can go about performing these functions, all of which are well documented in the Lua Reference Manual (similar to the online Java API). Link is at the end of the tutorial.

A lesson on I/O wouldn't be complete without some file manipulation. The io library (which is really a table, but more on that in the advanced tutorials) defaults to the stdout/stdin as previously discussed, but you can specify files to open, read, and write to, as illustrated by the following snippet:

--using to open a file

filename = "TextOne.txt"
file = assert(, "r"))
--assert can help us determine any errors
--opening modifiers are just like FILE* handlers in C
--*all reads the whole file, you can put it all in one variable
--not a problem like in other languages
--*line reads the next line, should be familliar
--*number reads a number from the filename
--num, reads a string with up to num characters

--I'll show an example of using both all and line:

--Make sure there is a text file in the same directory as your source
--name it whatever you want and change the above string

--my example textfile:
--This is text in a textfile!
--I am a large paragraph of text.
--I wish I had more text...
stringOne = file:read("*all")	--read it all
print("Whole thing:\n"..stringOne)

--rewind the seek pointer,
--those of you who have C/C++ experience will get this
--reread, only taking a line
stringTwo = file:read("*line")
print("\n\nSingle line:\n"..stringTwo)



Whole thing:
This is text in a textfile!
I am a large paragraph of text.
I wish I had more text...

Single line:
This is text in a textfile!

You can mix and match the simple/complete model as much as you want to fit your particular needs. For file I/O, there are many tricks and tips that are too lengthy to go into here, but know that Lua handles large strings very efficiently. Therefore it may make more sense to read in a file in its entirety and then sub-string, concatenate, etc... as needed. Using file:seek("end") will return the size of the file (very handy in certain situations!).

Files can be opened in binary/text mode just like in C/C++. Unix doesn't distinguish between them, but Windows does. Adding the 'b' tag to the file open attributes is all that is needed.

Please check out the Lua Reference Manual, as it contains full documentation on all of the libraries and functions, much more then I could cover in a single sitting. Look for this tutorial to pop up on your favorite programming help site in the next few days. I plan on having Advanced Lua - Part I out by the end of the week, tackling some interesting features of the language that will allow you to solve problems in ways other languages cannot. Happy coding!


Is This A Good Question/Topic? 0
  • +

Page 1 of 1