Main Content

Reading a data file and sensing EOF in Lua

Archive - Originally posted on "The Horse's Mouth" - 2009-08-10 18:25:18 - Graham Ellis

In Lua, the standard table io includes an io.open code element that lets you open a file. This returns a userdata to you (looks like a table but isn't - it's a C accessible structure) from which you can run the read code. Empty lines return an empty string (in Lua this is a TRUE value, unlike other languages), and at the end of file a nil is returned. See source code

You do need to write your reading loop as while true do, as you are not allowed to assign a value to a variable within the test condition - the = sign is not an operator in the same way that it is in other languages.

Covered on our Learning to Program in Lua course.