inputluaeof

How do I read until the end of file?


In C, I can read an input and stop the program when it reaches the end of file (EOF). Like so.

#include <stdio.h>

int main(void) {
    int a;       
    while (scanf("%d", &a) != EOF)
        printf("%d\n", a);
    return 0;
}

How can I do that in Lua?


Solution

  • The Lua Documentation features a ton of details on file-reading and other IO. For reading an entire file use:

    t = io.read("*all")
    

    The documentation has examples on reading line-by-line etc. Hope this helps.

    Example on reading all lines of a file and numbering each of them (line-by-line):

       local count = 1
        while true do
          local line = io.read()
          if line == nil then break end
          io.write(string.format("%6d  ", count), line, "\n")
          count = count + 1
        end