Read Data From a Txt File Lua

This offset edition was written for Lua 5.0. While withal largely relevant for later versions, there are some differences.
The fourth edition targets Lua v.3 and is bachelor at Amazon and other bookstores.
By buying the book, y'all also help to support the Lua projection.


21.one – The Elementary I/O Model

The unproblematic model does all of its operations on two electric current files. The library initializes the current input file equally the process's standard input (stdin) and the current output file equally the process's standard output (stdout). Therefore, when nosotros execute something like io.read(), we read a line from the standard input.

We tin can change those electric current files with the io.input and io.output functions. A call like io.input(filename) opens the given file (in read manner) and sets it as the current input file. From this bespeak on, all input will come from this file, until another call to io.input; io.output does a similar task for output. In case of errors, both functions raise the mistake. If you want to handle errors directly, you must use io.open, from the complete model.

Every bit write is simpler than read, we will expect at information technology commencement. The io.write function merely gets an arbitrary number of string arguments and writes them to the current output file. Numbers are converted to strings following the usual conversion rules; for full control over this conversion, you should utilise the format function, from the string library:

        > io.write("sin (3) = ", math.sin(3), "\due north")       --> sin (3) = 0.1411200080598672     > io.write(string.format("sin (3) = %.4f\n", math.sin(three)))       --> sin (3) = 0.1411      
Avert code like io.write(a..b..c); the telephone call io.write(a,b,c) accomplishes the aforementioned effect with fewer resources, as information technology avoids the concatenations.

Equally a dominion, you lot should use print for quick-and-dirty programs, or for debugging, and write when you need full control over your output:

        > print("hi", "Lua"); impress("Hello")       --> hello   Lua       --> Howdy          > io.write("hello", "Lua"); io.write("Hello", "\northward")       --> helloLuaHi      
Dissimilar print, write adds no actress characters to the output, such every bit tabs or newlines. Moreover, write uses the current output file, whereas impress ever uses the standard output. Finally, print automatically applies tostring to its arguments, so it can also show tables, functions, and nil.

The read function reads strings from the current input file. Its arguments command what is read:

"*all" reads the whole file
"*line" reads the side by side line
"*number" reads a number
num reads a string with upwardly to num characters

The call io.read("*all") reads the whole current input file, starting at its current position. If we are at the stop of file, or if the file is empty, the call returns an empty string.

Because Lua handles long strings efficiently, a simple technique for writing filters in Lua is to read the whole file into a string, practise the processing to the string (typically with gsub), and so write the cord to the output:

        t = io.read("*all")         -- read the whole file     t = cord.gsub(t, ...)     -- do the job     io.write(t)                 -- write the file      
Every bit an instance, the following code is a consummate program to lawmaking a file's content using the quoted-printable encoding of MIME. In this encoding, non-ASCII characters are coded as = XX, where XX is the numeric code of the character in hexadecimal. To keep the consistency of the encoding, the `=´ character must be encoded equally well. The blueprint used in the gsub captures all characters with codes from 128 to 255, plus the equal sign.
        t = io.read("*all")     t = string.gsub(t, "([\128-\255=])", function (c)           return string.format("=%02X", cord.byte(c))         stop)     io.write(t)      
On a Pentium 333MHz, this plan takes 0.ii seconds to convert a file with 200K characters.

The telephone call io.read("*line") returns the adjacent line from the current input file, without the newline graphic symbol. When we accomplish the stop of file, the telephone call returns nix (as in that location is no adjacent line to return). This blueprint is the default for read, and so io.read() has the same effect as io.read("*line"). Usually, we use this pattern simply when our algorithm naturally handles the file line past line; otherwise, we favor reading the whole file at in one case, with *all, or in blocks, as we will run into after. As a uncomplicated example of the utilize of this blueprint, the following program copies its current input to the current output, numbering each line:

        local count = ane     while truthful do       local line = io.read()       if line == nil then break terminate       io.write(cord.format("%6d  ", count), line, "\n")       count = count + 1     terminate      
Even so, to iterate on a whole file line past line, we do improve to use the io.lines iterator. For example, we can write a complete program to sort the lines of a file as follows:
        local lines = {}     -- read the lines in table 'lines'     for line in io.lines() do       tabular array.insert(lines, line)     end     -- sort     table.sort(lines)     -- write all the lines     for i, fifty in ipairs(lines) practise io.write(l, "\northward") terminate      
This program sorts a file with iv.v MB (32K lines) in 1.viii seconds (on a Pentium 333MHz), confronting 0.half dozen seconds spent by the system sort program, which is written in C and highly optimized.

The call io.read("*number") reads a number from the current input file. This is the only case where read returns a number, instead of a string. When you need to read many numbers from a file, the absence of the intermediate strings can make a meaning performance improvement. The *number option skips any spaces before the number and accepts number formats like -3, +5.2, chiliad, and -3.4e-23. If information technology cannot notice a number at the current file position (because of bad format or end of file), it returns nil.

You can call read with multiple options; for each statement, the role will render the respective result. Suppose you take a file with iii numbers per line:

        6.0       -3.23     15e12     4.three       234       1000001     ...      
Now you want to print the maximum of each line. Yous can read all three numbers in a unmarried phone call to read:
        while truthful practise       local n1, n2, n3 = io.read("*number", "*number",                                  "*number")       if not n1 then intermission end       print(math.max(n1, n2, n3))     end      
In any case, you should e'er consider the alternative of reading the whole file with choice "*all" from io.read and and so using gfind to suspension it upward:
        local pat = "(%S+)%due south+(%S+)%s+(%S+)%s+"     for n1, n2, n3 in cord.gfind(io.read("*all"), pat) exercise       print(math.max(n1, n2, n3))     end      

Besides the basic read patterns, you can call read with a number n as argument: In this case, read tries to read n characters from the input file. If it cannot read whatsoever character (end of file), read returns zip; otherwise, it returns a cord with at most north characters. Every bit an example of this read pattern, the following programme is an efficient way (in Lua, of form) to copy a file from stdin to stdout:

        local size = 2^13      -- good buffer size (8K)     while true do       local block = io.read(size)       if non cake and then break end       io.write(cake)     end      

Every bit a special case, io.read(0) works as a test for end of file: Information technology returns an empty string if there is more to be read or nil otherwise.


austinameat1978.blogspot.com

Source: https://www.lua.org/pil/21.1.html

Belum ada Komentar untuk "Read Data From a Txt File Lua"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel