Some examples of common function libraries in Lua explain _lua

Source: Internet
Author: User
Tags current time flush lowercase lua mathematical functions sin time and date

Objective

This article will come with some easy content, simply introducing a few common libraries in Lua. Simply put, a few APIs are introduced. So, it looks easier, and it's not much weight. is a pure summary. The use of libraries is to facilitate our development, improve development efficiency, but also to ensure the quality of the code. I hope you will not repeat the wheel.

Math Library

The Mathematical Library (math) is composed of a set of standard mathematical functions. Here mainly introduces a few commonly used functions, other people can solve their own Baidu.

Trigonometric Functions (Sin,cos,tan ...) )

All trigonometric functions use radians, and you can convert angles and radians with function deg (angles) and rad (radians). Sample code:

Copy Code code as follows:

Print (Math.sin (Math.rad (30))--0.5

Remember: trigonometric function parameters are radians, in the actual use do not forget, is radians.

Take the whole function (Floor,ceil)

Floor: Returns the largest integer not greater than X, rounding down;
Ceil: Returns the largest integer, not less than X, rounding up. Sample code:

Copy Code code as follows:

Print (Math.floor (5.6))--5
Print (Math.ceil (5.6))--6

Maximum and minimum values (max,min)

Max: Takes the maximum value in the parameter;
Min: Takes the minimum value from the parameter. Sample code:

Copy Code code as follows:

Print (Math.max (2, 3, 2, 14, 2, 30,-3))--30
Print (Math.min (2, 3, 2, 2,-3))---3

A function to generate pseudorandom numbers (random,randomseed)

In actual development, the demand for generating random numbers is often available. Using random and Randomseed these two functions can be done easily. Math.random is used to generate pseudo random numbers, which can be invoked in 3 ways:
(1) If no arguments are supplied at the time of the call, it returns a pseudo random real number uniformly distributed within the interval [0, 1);
(2) If an integer n is provided as a parameter, it returns a pseudo random integer in the interval [1, n];
(3) If two integer parameters m and n are provided, it returns a pseudo random integer in the interval [m, n].
The sample code is as follows:

Copy Code code as follows:

Print (Math.random ())--outputs a value greater than or equal to 0, less than 1
Print (Math.random (2))--the output is either 1 or 2
Print (Math.random (3, 4))--output is either 3 or 4

If you follow the above code and then look at the comments I wrote, you may have to scold me, what broke the annotation, is clearly wrong? The output of each run is the same. Yes, the result is the same, this is going to be about the upcoming math.randomseed. function math.randomseed is used to set the number of seeds for pseudorandom number generators. (see here, I think you're a person who has had a year of programming experience, so, you don't ask me what is the seed, this conceptual thing, I think Baidu Encyclopedia or Wikipedia than I have more guiding significance) Math.randomseed's only argument is a value we call the seed number. It is generally our practice to initialize a pseudo random number generator by calling it with a fixed number of seeds at the start of a program. So how do you set the seed value of this math.randomseed? If you use the same seed value, the random number will be the same each time, in actual development, usually use the current time as a seed value, such as:

Copy Code code as follows:

Math.randomseed (Os.time ())

That's good. In general, when our program starts, it's enough to initialize the seed once. I used to be silly. In a loop, use Math.random to take random numbers, and each time you call Math.randomseed (Os.time ()) Set the seed value (why not?). You can try it on your own and see the results. If you do not understand, leave your confusion, we continue to communicate.
Copy Code code as follows:

Math.randomseed (Os.time ())
Print (Math.random ())--outputs a value greater than or equal to 0, less than 1
Print (Math.random (2))--the output is either 1 or 2
Print (Math.random (3, 4))--output is either 3 or 4

That's all right, run it and see the results.

Table Gallery

The table library is made up of auxiliary functions that manipulate the table as an array (emphasis: operation as an array).

Insert and DELETE functions

Table.insert is used to insert an element into the specified position of an array, which moves subsequent elements to empty space. If a positional argument is not specified when Table.insert is invoked, the element is added to the end of the array. Sample code:

Copy Code code as follows:

Local TB = {10, 20, 30}
Table.insert (TB, 40)--at the end of the table insert, the result is: {10, 20, 30, 40}
Table.insert (TB, 2, 15)--Insert at table 2, result: {10, 15, 20, 30, 40}

The function Table.remove deletes and returns the element at the specified position of the array, and moves all elements after that position forward to fill the vacancy. If you do not specify a positional argument when calling this function, it deletes the last element of the array. Sample code:
Copy Code code as follows:

Local TB = {10, 20, 30}
Print (Table.remove (TB))--Deletes the last element and returns 30; Finally, TB = {10, 20}
Print (Table.remove (TB, 1))--Deletes the first element and returns 10; Finally, TB = {20}

Now with both operations, it's easy to implement the stack in the data structure. Wait for what? Try it yourself.

Sort

To sort the array, this requirement, which was encountered in the actual development of 100%. So, it's not going to be sorted using LUA arrays, which can be laughed by others. Talk less. In Lua, we can use Table.sort to accomplish this task. It can sort an array, and you can specify an optional order function. This order function has two parameters and should return TRUE if you want the first argument to precede the second parameter value in the sort result, and if this function is not supplied, Table.sort uses the default less action. Instance code:

Copy Code code as follows:

Local TB = {20, 10, 2, 3, 4, 89, 20, 33, 2, 3}

--The default is ascending sort
Table.sort (TB)
For _, V. in Ipairs (TB) do
Print (v)
End

Print ("=======")

--Modify to descending sort
Table.sort (TB, function (A, B) if a > B then return True end)
For _, V. in Ipairs (TB) do
Print (v)
End

However, in actual development, we often make such a mistake, always trying to sort the index of a table. In the table, the index is an unordered collection. If you sort them, you must copy them into an array and then sort the array. That's why I started by emphasizing that the table library operates on an array of arrays. Sample code:
Copy Code code as follows:

Local TB = {x = =, z = 2, n = 8}--This is a key unordered table
--If you want to rank the key in ascending order, the following code does not work
Table.sort (TB)
For K, v. in pairs (TB) do
Print (K.. " = " .. V
End

The correct approach is to put all the keys of this table into an array and sort the array. Sample code:
Copy Code code as follows:

Local TB = {x = =, z = 2, n = 8}--This is a key unordered table

Local KEYTB = {}
For k, _ in pairs (TB) do
keytb[#keyTb + 1] = k
End

Table.sort (KEYTB)

For _, V. in Ipairs (KEYTB) do
Print (v... " = " .. TB[V])
End

Now it's in ascending order of key.

Connection

Use Table.concat to complete the array connection. It takes an array of strings and returns the result of the concatenation of these strings, which has an optional parameter that specifies the delimiter to be inserted between the strings, and the function also accepts two optional arguments to specify the first and last string index to concatenate. Sample code:

Copy Code code as follows:

Local TB = {"Jelly", "I", "is", "good"}
Local STRTB = Table.concat (TB, "")
Print (STRTB)

String Library

The point is, to learn each language, in the actual work, we are always dealing with strings. Lua is no exception, and in Lua the true string manipulation comes from the string library, where all functions in the string library are exported in a module string. Now let's summarize the string library.

Underlying string functions

Just go through the Code, sample code:

Copy Code code as follows:

Local str = "Jelly"

--String.len can get the length of the string
Local len = String.len (str)
Print (len)--11

--String.rep Returns the result of the string repeat n times
str = "AB"
Local NEWSTR = String.rep (str, 2)--repeat two times
Print (NEWSTR)--Abab

--String.Lower the string lowercase to uppercase and returns a copy of the change
str = "Jelly"
NEWSTR = String.Lower (str)
Print (NEWSTR)--jelly

--String.upper the string into lowercase and returns a copy of the change
NEWSTR = String.upper (str)
Print (NEWSTR)--JELLY

Here is an introduction to the String.sub (s, I, j) functions, which can extract the first and the J characters from the string s. In Lua, the first character of a string is indexed with 1, but the index can also be a negative number, representing the end of the string, with index-1 representing the last character of the string, and so on.
Copy Code code as follows:

Local str = "[Jelly]"
Local NEWSTR = String.sub (str, 2,-2)
Print (NEWSTR)--Jelly
NEWSTR = String.sub (str, 2, 6)
Print (NEWSTR)--Jelly

(emphasis: In Lua, strings are immutable like other languages, and all of these actions return a new value, but do not modify the original string.) Keep in mind that I remember!!! )
function String.char and function string.byte are used to convert characters and their internal numeric representations; The String.char function accepts 0 or more integers, converts each integer to the corresponding character, and then returns a string connected by those characters. String.byte (S, i) returns an internal numeric representation of the first character in the string s, and its second argument is optional, and calling String.byte (s) returns an internal numeric representation of the number one character in the string S. Sample code:
Copy Code code as follows:

Print (String.char)--A

Local i = 98
Print (String.char (i, i + 1, i + 2))--BCD

Print (String.byte ("abc"))--97
Print (String.byte ("abc", 2))--98
Print (String.byte ("abc", 2, 3)--98 99
Print (String.byte ("abc",-1))--99

There's also a magical function in Lua, String.Format. is consistent with printf in the C language. It's amazing because it's used too much and it's very useful. So I have no more nonsense here, I believe you will all.

Pattern matching

Because the pattern matches a lot of things, so prepare to write a separate blog post summary.

I/O Library

The I/O library provides two different models for file operations, a simple model and a complete model. The simple model assumes that there is a current input file and a current output file, and that its I/O operations are used for these files. The full model uses an explicit file handle. It takes an object-oriented style and defines all the actions as a method on a file handle.

Simple I/O model

All operations of the simple model are used for two current files. The I/O library initializes the current input file to process standard input (stdin) and initializes the current output file to the process standard output. When the Io.read () operation is performed, a row is read from the standard input.

The two current files can be changed with function Io.input and io.output. The io.input (filename) Call opens the specified file in read-only mode and sets it as the current input file, and unless the io.input is invoked again, all input will come from that file, and Io.output can do the same with the output. said the input and output, in to chat Io.write and Io.read.

Io.write accepts any number of string parameters and writes them to the current output file; It can also accept numeric parameters, which are converted to strings based on regular conversion rules. If you want more control, you can use String.Format for control. function Io.read reads a string from the current input file, and its arguments determine the data to read:

"*all" Read the entire file
"*line" Read Next line
"*number" Read a number
<num> Read a string that does not exceed <num> characters

Just look at a sample code:

Copy Code code as follows:

--Establish Input.txt and output.txt two files first
--Write the following in the Input.txt file:
--[[
Http://www.jb51.net
Jelly Think | An original article sharing site
88
--]]
Io.input ("Input.txt")--read from Input.txt file
Io.output ("Output.txt")--write to Output.txt file

--write some test data to Input.txt
Io.write ("Jellythink", "\ n")
Io.write ("Jelly thought", "\ n")
Io.write ("http://www.jb51.net", "\ n")
Io.write (88)

Read sample code for an entire file:

Copy Code code as follows:

str = io.read ("*all")--Reads all
--[[
Print (str)
Http://www.jb51.net
Jelly Think | An original article sharing site
88
--]]
Print (str)

Read one line of sample code at a time:

Copy Code code as follows:

--to determine whether you have read the end of the file
-If it's already at the end, return to nil, or return an empty string
Local mark = io.read (0)
While Mark does
Print (Io.read ("*line"))
Mark = Io.read (0)
If not Mark then
Print ("File end.")
Break
End
End

Full I/O model

The simple I/O feature is so limited that it is basically useless, and more is the full I/O model here. The full I/O model can do more I/O control, which is based on the file handle, like the file* in C, which represents an operating file.

To open a file, you can use the Io.open function, which has two arguments, one that represents the file name to open, and another that represents the operation's pattern string. The pattern string can have the following four methods of value:

(1) "R": Open the file as read, and only read the file;
(2) "W": Open the file as write, write to the file, but overwrite the original contents of the file;
(3) "A": Open the file as an append, write to the file, and append it to the base of the original file;
(4) "B": to open the binary file, this mode is generally and the previous three mixed use, such as: "RB", "WB."

The open function returns a handle that represents the file, and if an error occurs, it returns nil, an error message, and an error code. Sample code:

Copy Code code as follows:

--access to a nonexistent file
Print (Io.open ("Ooxx.txt", R))
--[[
Output the following:
Nil ooxx.txt:No such file or directory 2
--]]

After a successful opening of a file, you can use the Read/write method to read and write files, similar to the Read/write function, but you need to use the colon syntax as a file handle method to invoke, sample code:

Copy Code code as follows:

Local hfile = Io.open ("Input.txt", R)
If Hfile Then
Local strcontent = Hfile:read ("*all")
--local strcontent = Hfile.read (hfile, "*all") You can also use this method
Print (strcontent)
End

We can also mix the full I/O pattern with the simple I/O pattern. You can get a handle to the current input file by calling Io.input () without specifying a parameter, and by Io.input (handle), you can set the handle to the current input file, for example, if you need to temporarily change the current input file:
Copy Code code as follows:

--Io.input () Gets the current input file handle when the argument is not passed in
Local hcurrent = Io.input ()

--Open a new file
Io.input ("Input.txt")

--Operate on a new file
Local strcontent = Io.read ("*all")
Print (strcontent)

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

--After the operation completes, restores to the previous state
Io.input (hcurrent)

Other file Actions

function Tmpfile returns a handle to a temporary file that is opened in read/write mode and is automatically deleted at the end of the program. When we use, we can directly io.tmpfile () on the OK.
The function flush writes the data in the buffer to the file, which, like the Write function, Io.flush () refreshes the current output file when it is called as a function, and F:flush () refreshes a particular file F when it is invoked as a method.

function seek to get and set the current location of a file. Its general form is f:seek (whence, offset), and its parameters have the following specific meanings:

(1) The whence value Set,offset is expressed as the offset from the beginning of the file;
(2) The whence Cur,offset is expressed as an offset relative to the current position;
(3) The whence value End,offset is expressed as an offset from the end of the file.

The return value of a function is independent of whence, which always returns the current position of the file, that is, the number of offset bytes at the beginning of the file. Based on the description above, here's a short sample code:

Copy Code code as follows:

function GetFileSize (hfile)
Local Currentpos = Hfile:seek ()--Get current position
Local size = File:seek (' End ')--Get file size
File:seek ("Set", Currentpos)
return size
End

Operating system functions

The operating system library is defined in the table OS, which contains functions for file manipulation functions, for obtaining the current date and time. To ensure the portability of LUA, it is simpler for a file library, which contains only two functions:

os.rename function for file renaming;
The Os.remove function to delete the file.

But it is necessary to take a moment to sum up the function of getting the date and time.

Date and time

There are two very important date and time functions available in the LUA library, respectively time and date. Let's start with the time function.

Time

If the time function is called without any arguments, it returns the current date and time in numeric form. The returned value represents the number of seconds in the current time to a specific time, and this particular time is not the same on different systems. If invoked with a table as an argument, it returns a number that represents the date and time described in the table. This table has the following valid fields:

Year A full year
Month 01-12
Day 01-31
Hour 00-23
Min 00-59
Sec 00-59
Isdst A Boolean value, True indicates daylight saving time

The first three fields must be available, such as:

Copy Code code as follows:

Print (Os.time ())--Prints the description of the current time
Print (Os.time ({year=2014,month=8,day=14}))

Date

The function date is an inverse function of time that converts a number representing a date and times to some advanced representations. The first argument is the format string, the expected representation is specified, and the second parameter is the number of the date and time, which defaults to the current date and time. For example:

Copy Code code as follows:

Local tbcurrenttime = Os.date ("*t")

For K, V-pairs (tbcurrenttime) do
Print (K.. "=" .. ToString (v))
End

This will output the time of day, you run the following code to see. In fact, the data function does not have much to say. The data function is just the first parameter of the format type is very many, you can go to Baidu. I usually use a *t is enough. But it's also good to know the rest.

For the time and date two functions mentioned here, general time function return description is not suitable for people to read, we generally save this number, in the background for processing; for the date function, the returned content is appropriate for people to read, so the data returned by date is typically displayed on the UI.

Summarize

For any language, a standard library is a very large thing, as is LUA, so this article is also relatively long. Sorry, this is just the first part, and there is a second part behind it. So, let's all just look at it. Although the depth of things are not much, but this is the way we get started a language. Young men, try hard.

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.