Recently, while writing some bat tools, I found myself having little knowledge of Lua's IO and regular expression usage, and reprinted articles on the web that solved the problem. _lua

Source: Internet
Author: User
Tags assert lua numeric value sin stdin

Function prototypes String.gsub (S, Pat, Repl [, N])

is the global substitution substring.
S: source string
Pat: pattern, matching mode
Repl:replacement, replace the string that the PAT matches with the REPL
[, N]: optional, to see only the first n characters of the source string

For example, write a trim function: [Plain] View plain copy function trim (s) return (String.gsub (S, "^%s* (.-)%s*$", "%1")) end----and then call: S = ' \ t a BC d ' Print (trim (s))-----output: A BC D, the beginning of \ T, the end of the space was trim off

Here are a few things to explain:
1. Return (String.gsub (...)), notice that there is also a bracket outside the string.gsub. In fact, the GSUB call returns two values, one is the replacement string and the second is the number of replacements. Once the outer brackets are added, only the first value, the replacement string, is returned. You can try to remove the outer brackets and see what the output is.

2. Match the pattern string "^...$" to indicate that the match is the entire character. ^ Table opening, $ indicates end. Here, the effect of (.-) should be the same as the (. *) effect, since it is always matched from the beginning of the string to the end.
If you remove ^ and $, then you are not matching the entire string, and in the (.-) function, the output becomes: ABCD is linked together


Lua----The use of LFS libraries

Lfs.attributes (filepath [, Aname]) Gets the path specified property
Lfs.chdir (path) changes the current working directory, returns true successfully, fails back nil plus error message
Lfs.currentdir get the current working directory, successfully return the path, failure nil plus error message
Lfs.dir (path) returns an iterator (function) and a directory (UserData), and each iterator returns a path until it is not a file directory, and the iterator returns nil
Lfs.lock (FileHandle, mode[, start[, length])
Lfs.mkdir (dirname) creates a new directory
Lfs.rmdir (dirname) deletes an existing directory, returns true successfully, fails back nil plus error message



Lua Standard library-input and output processing (inputs and outputs facilities) Editor: Cynthia Author: from itpub forum 2008-02-18 text Tag:lua

"IT168 Technical Documentation" I/O library provides two different ways to do file processing

1, IO table invocation mode: Using IO table, Io.open will return the description of the specified file, and all operations will be described around this file

The IO table also provides three predefined file descriptions Io.stdin,io.stdout,io.stderr

2, the file handle direct call way, that is, using the file:xxx () function mode, where file is Io.open () returned by the handle

When most I/O function calls fail, return nil plus error messages, and some functions return nil when they succeed

1, Io.close ([file])

Function: equivalent to File:close (), close the default output file

2, Io.flush ()

Function: equivalent to File:flush (), output all buffered content to the default output file

3, Io.lines ([filename])

Function: Open the specified file filename read mode and return an iterative function, each call will get a line of content in the file, when the end of the file, will return to nil, and automatically close the file

If not with the parameter Io.lines () <=> io.input (): lines (); Reads the contents of the default input device, but does not close the file at the end

such as: For Line in Io.lines ("Main.lua") do

Print (line)

End

4, Io.open (filename [, mode])

Function: Opens a file in the specified mode, returns the file handle successfully, and returns nil+ error message if it fails

Mode

"R": Read mode (default);

"W": Write mode;

"A": Add mode;

"r+": Update mode, all previous data will be saved

"w+": Update mode, all previous data will be cleared

"A +": Add update mode, all previous data will be saved, only allowed at the end of the file to add

"B": Some systems support binary mode

5, Io.output ([file])

Function: equivalent to io.input, but operation on the default output file

6, Io.popen ([prog [, mode]])

Function: Start the program prog the additional process and return the file handle for prog (not all system platforms are supported)

7, Io.read (...)

Function: equivalent to Io.input (): Read

8, Io.tmpfile ()

Function: Returns a temporary file handle that is opened in update mode and automatically deleted at the end of the program

9, Io.type (obj)

Function: Detects if obj is an available file handle

Return:

' file ': Handle for an open file handle

"Closed file": A closed file handle

Nil: Indicates that obj is not a file handle

10, Io.write (...)

Function: equivalent to Io.output (): Write

11, File:close ()

Features: Closing files

Note: When a file handle is garbage collected, the file is automatically closed. Handle will become an unpredictable value

12, File:flush ()

Function: Writes all data in the buffer to the file

13, File:lines ()

Function: Returns an iterative function, each call will get a line of content in the file, when the end of the file, will return nil, but do not close the file

such as: For Line in File:lines ()

14, File:read (...)

Function: Reads a file in the specified format, returns a string or number by each format function, and returns nil if not read correctly, if no format is specified to read by default.

Format:

"*n": Reading a number (*number)

"*a": reads the entire file from the current position and, if the end of the file, returns an empty string (writable *all)

"*l": [Default] reads the contents of the next line, if the end of the file, then returns Nil (*line)

Number: Reads the character of the specified byte count, if the end of the file, returns nil; If number is 0 then return the empty string, if the end of the file, then return nil;

The Read function reads the string from the current input file and controls what is read by its parameters:

"*all"

Read the entire file

"*line"

Read Next line

"*number"

Converts a numeric value from a string

Num

Reading num characters to a string

15, File:seek ([Whence][,offset])

Function: Set and get the current file location, Success returns the final file location (in bytes), Failure returns nil plus error message

Parameters

Whence:

"Set": Starting from the file header

"cur": starting at current position [default]

"End": Starting at the ends of a file

Offset: defaults to 0

File:seek () With no arguments returns the current position, File:seek ("set") navigates to the file header, File:seek ("End") navigates to the tail of the file and returns the file size

16, File:setvbuf (Mode,[,size])

Function: Set buffer mode for output file

Parameters

Mode

"No": no buffer, i.e. direct output

"Full": Fully buffered, that is, when the buffer is full before the output operation (also can call flush immediately output)

"line": output in units of behavior (more for terminal equipment)

The last two modes, size can specify the size of the buffer (in bytes), and ignoring size automatically adjusts to the optimal size

17, File:write (...)

Function: Output file contents in the specified parameter format, parameters must be characters or numbers, and to output other values, you need to convert through ToString or String.Format


The I/O library provides two modes of file operation. Simple mode has a current input file and a current output file, and provides actions related to those files. Full mode (complete model) is implemented using external file handles. It defines all file operations as a method of file handles in the form of objects. Simple mode is more appropriate when doing some simple file operations. We have been using it in the earlier part of the book. But in some advanced file operations, simple mode is not enough. For example, to read multiple files at the same time, using full mode is more appropriate. All functions of the I/O library are placed in table IO.

21.1 Simple I/O mode

All operations in simple mode are on top of two current files. The I/O library takes the current input file as standard input (stdin) and takes the current output file as standard output (stdout). So when we execute io.read, we read one line in the standard input. We can use the Io.input and Io.output functions to change the current file. For example, io.input (filename) opens the given file (in read mode) and sets it to the current input file. All the input is then from this text until you use Io.input again. Io.output function. Similar to Io.input. Two functions that produce an error will generate an error. If you want to control the error directly, you must use the Io.read function in full mode. Write operation is simpler than read operation, we start with the write operation. In the following example, the function Io.write gets any number of string arguments, and then writes them to the current output file. Usually a number is converted to a string according to the usual rules, if you want to control this conversion, you can use the Format function in the string library:

> Io.write ("sin (3) =", Math.sin (3), "/n")

--> sin (3) = 0.1411200080598672

> Io.write (String.Format ("sin (3) =%.4f/n", Math.sin (3)))

--> sin (3) = 0.1411

You should avoid writing code like Io.write (A. B.. c); This writing is the same as the effect of Io.write (A,B,C). However, the latter consumes less resources because of the avoidance of inline operations. In principle, you use the print function when you are making rough (quick and dirty) programming, or you are scheduling errors. Write is used when the output needs to be fully controlled.

> Print ("Hello", "Lua"); Print ("Hi")

--> Hello Lua

--> Hi

> io.write ("Hello", "Lua"); Io.write ("Hi", "n")

--> Helloluahi

The write function differs from the print function in that write does not append any extra characters to the output, such as tabs, line breaks, and so on. And the Write function uses the current output file, and print always uses standard output. In addition, the print function automatically invokes the parameter's ToString method, so you can display the tables (tables) function (functions) and nil.

The Read function reads the string from the current input file and controls what is read by its parameters:

"*all"

Read the entire file

"*line"

Read Next line

"*number"

Converts a numeric value from a string

Num

Reading num characters to a string

The Io.read ("*all") function reads the entire input file from its current location. If the current position is at the end of the file, or if the file is empty, the function returns an empty string. Because of LUA's efficient management of long string type values, a simple way to use filters in Lua is to read the entire file into a string, after processing it (for example, using function Gsub), and then writing to the output:

t = Io.read ("*all")--Read the whole file

t = string.gsub (t, ...) --Do the job

Io.write (t)--Write the file

The following code is an example of a complete process string. The contents of the file are encoded using the Quoted-printable code in MIME (Multipurpose Internet Mail Extension Protocol). Encoded in this form, non-ASCII characters will be encoded as "=xx", where XX is the hexadecimal representation of the character value, and the same requirement is rewritten for the consistency "=" character. The function of the "mode" parameter in the Gsub function is to get all the characters between 128 and 255, and add an equal sign to them.

t = Io.read ("*all")

t = string.gsub (T, "([/128-/255=])", function (c)

Return String.Format ("=x", String.byte (c))

End

Io.write (t)

It takes 0.2 seconds for the program to convert 200k characters in the Pentium 333MHz environment.

The Io.read ("*line") function returns the next line of the current input file (does not contain the last line feed). When the end of the file is reached, the return value is nil (indicates that there is no next line to return). The Read method is the default for the read function, so it can be abbreviated to Io.read (). This is usually the way to read a file because the operation of the file is done on a line-by-row basis, or more inclined to use *all to read the entire file at a time, or to read the file block by piece later. The following program shows how you should use this mode to read files. This program copies the current input file to the output file and records the number of rows.

Local count = 1

While True

Local line = Io.read ()

if line = = Nil then break end

Io.write (String.Format ("M", count), line, "/n")

Count = Count + 1

End

However, in order to iterate through the entire file. We'd better use a io.lines iterator. For example, the procedure for sorting the rows of a file is as follows:

Local lines = {}

--Read the lines in table ' lines '

For line in Io.lines () do

Table.insert (lines, line)

End

--Sort

Table.sort (lines)

--Write all the lines

For I, L-ipairs (lines) do Io.write (L, "n") end

On Pentium 333MHz The program handles 4.5MB size, 32K rows of files takes 1.8 seconds, faster than 0.6 seconds to sort programs using highly optimized C language systems. The Io.read ("*number") function reads a numeric value from the current input file. The read function only returns a numeric value, not a string, under this parameter. When you need to read a large number of numbers from a file, the string between numbers is blank, which can significantly improve performance. The *number option skips any space between two recognizable digits. These recognizable strings can be-3, +5.2, 1000, and -3.4e-23. If a number is not found in the current position (due to the wrong format, or to the end of the file), return nil can set the options for each parameter, and the function will return the respective results. If there is a file containing three digits per line:

6.0-3.23 15e12

4.3 234 1000001

...

Now to print out the largest number of each row, you can use a read function call to read out all three digits of each row:

While True

Local N1, n2, N3 = Io.read ("*number", "*number", "*number")

If not N1 then break end

Print (Math.max (N1, N2, N3))

End

In any case, you should consider selecting the "*.all" option to use the Io.read function to read the entire file, and then use the Gfind function to decompose:

Local Pat = "(%s+)%s+ (%s+)%s+ (%s+)%s+"

For N1, N2, N3 in String.gfind (Io.read ("*all"), Pat) do

Print (Math.max (N1, N2, N3))

End

In addition to the basic read mode, you can also use the value n as the parameter of the Read function. In this case, the read function will attempt to read n characters from the input file. If no characters can be read (already at the end of the file), the function returns to nil. Otherwise, a string that contains up to n characters is returned. The following is an example program for efficient file copying of the read function parameter (in Lua, of course)

Local size = 2^13--Good buffer size (8K)

While True

Local block = io.read (size)

If not blocks then break end

Io.write (Block)

End

In particular, the Io.read (0) function can be used to test whether the end of the file has been reached. If you are not returning an empty string, return nil if it is already at the end of the file.

21.2 Full I/O mode

For more comprehensive control of input and output, you can use full mode. The core of the full pattern is the file handle (handle). This structure resembles the file flow (file*) in C, which renders an open file and the current access location. The function to open a file is Io.open. It mimics the fopen function in C, and also needs to open the file's filename parameter and open the pattern's string argument. The pattern string can be "R" (read mode), "W" (write mode, overwrite data), or "a" (Attach mode). And the character "B" can be appended to the following representation to open the file in binary form. Normally, the Open function returns a handle to a file. If an error occurs, the nil is returned, along with an error message and error code.

Print (Io.open ("Non-existent file", "R"))

--> nil No such file or directory 2

Print (Io.open ("/etc/passwd", "w"))

--> Nil Permission denied 13

The definition of the error code is determined by the system.

The following is a typical code to check for errors:

Local F = assert (Io.open (filename, mode)

If the open function fails and the error message is an assert argument, the information is displayed by assert. Once the files are open, they can be read and written by using the Read and write methods. They are similar to the read/write functions of IO tables, but different invocation methods must be called by using the colon character as a method of the file handle. For example, open a file and read it all. You can use the following code.

Local F = assert (Io.open (filename, "R"))

Local T = f:read ("*all")

F:close ()

Similar to the stream settings in C, the I/O library provides three predefined handles: Io.stdin, Io.stdout, and Io.stderr. Therefore, you can send the message directly to the error stream using the following code.

Io.stderr:write (Message)

We can also mix the full mode and the simple pattern. Use the Io.input () function without any arguments to get the current input file handle, and use the io.input (handle) function with parameters to set the input file that the current input file represents for the handle handle. (Same usage applies to io.output functions) for example, to implement a temporary change to the current input file, you can use the following code:

Local temp = Io.input ()--Save current file

Io.input ("Newinput")--open a new current file

...--do something with new input

Io.input (): Close ()--Close current file

Io.input (temp)--Restore previous current file

A little tip for 21.2.1 I/O optimization

Because in general Lua reads the entire

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.