Lua's string and string library summary

Source: Internet
Author: User

LUA has 7 types of data, namely nil, Boolean, number, string, table, function, UserData. Here I summarize the string type of Lua and the string library and review it to deepen the memory.

The individual considers string to be second only to the type of table when Lua uses data structures for programming. Very IMPORTANT!

First, string basis.

LUA does not have a character type, and Lua's string type represents a sequence of characters. Therefore, a string of length 1 represents a single character. The character types of Lua have these characteristics:

1. The characters in the string character sequence are fully 8-bit encoded, which means that any binary data can be stored.

2, string is an immutable value. Equivalent to the String class in Java. Each modification returns a new string, while the original string remains unchanged. Such as:

" ABC "  ="CBA"print(a)        -->CBA  Print(b)        -->abc

3, string literal value, with matching single quotation marks, double quotation marks around the line. You can also use the backslash "\" escape sequence as in other languages. Such as:

c = ' abc\ndef '            print(c)        -    -> output is newline

4. You can specify the characters in the string by < escape character "\" + Value >, and the number is a sequence of up to 3 digits. Such as:

" \97\98c " Print (d)        -- ABC

5, you can use a pair of [[XXX]] to define a string XXX. The string can be any character. Such as:

[It's Mine!it's not yours!--' Oh '-   -"WOW!!!!" ]print (e)        -- output all contents of [[]]

6. The above indicates that there is a bug, that is, when the string contains [[or]] substrings, the error is expressed. LUA provides a form such as [===[xxx]===] to contain the string XXX. Where the number of "=" between the brackets between the two sides is matched. Such as:

[==[abc[=]defgh[[=]]]==] Print (f)        -- abc[=]defgh[[=]]

7. LUA provides automatic conversion of run-time numbers and characters. That is, a number and a string are added, and LUA attempts to convert the string to a number and then evaluate it. We do not need an explicit conversion. Such as:

Print ("5"+6)        --  One Print ("5e-2"+3)        -- 3.05

8, the length operator "#", can be used to find the length of the string, that is, the string contains the number of characters. Such as:

Print (#"abcd\n")    -- 5 " ABC " Print (#str)            -- 3

Second, String library

(Popular science, it is estimated that a lot of Lua beginners and I like the first time to see the LUA API will be very strange, like String.byte (s [, I [, J]]) What are these "[]"? Hehe, the brackets represent the optional parameters.

That is, it can be called: String.byte ("abc"), or it can be called: String.byte ("abc", 1), of course, can also call: String.byte ("abc", 1,-1);)

Detailed explanation of the API don't reinvent the wheel, cloud God has already translated, look here, here I briefly explain.

1,String.byte (s [, I [, J]])

Returns the internal numeric encoding of the string, I, J for the index of the string, and the number of characters I, J, returns. As follows:

String.byte ("abcdef",1,3) Print (K1,K2,K3)    --     98    

2,String.char (...)

In contrast to Byte (), converts the numeric encoding to a string. As follows:

s =String.char( the,98, About)Print(s)--ABCN=String.char()Print(n)--There 's nothing out there.Print(type(n))--stringPrint(String.char(String.byte("Hello",1,-2)))--Hell

3.string.dump (function [, strip])

This function is used to serialize the function. Passes in a function that returns a string. The function can be deserialized by means of the load string. Use the following:

functionMax (A, b)returnA>b andAorbEnd--Serialization ofDu =String.dump(max)Print(type(DU))--stringPrint(DU)--Luaq--deserializationMAX2 =Load(du)--calling FunctionsPrint(Max2 (1,2))--2

4,string.find (s, pattern [, init [, Plain]])

The function, such as its name, is used to find the matching pattern, returning the index of the pattern. A match is found to return. If not found, returns NULL. As follows:

TXT ="it ' s very very good!"I, J=String.find(TXT,"very")Print(I,J)--6 9I, j =String.find(TXT,"Big")Print(I,J)--Nil Nil  

5,String.Format (formatstring,)

This function is used to format the string. The API documentation is complex and has many uses to view documents. As follows:

Print (String.Format("I want%d apples"5))    -- I want 5 apples

6, String.match (s, pattern [, Init])

This function is similar to the Find () function, where find returns a matching index, which returns the first matching content itself, as follows:

Print (String.Format("I want%d apples"5))    -- I want 5 apples

7,String.gmatch (s, pattern)

This function is basically used with a for loop, and returns an iterator function that returns a value that matches that string each time the iterator function is called.

The example in the Lua5.3 reference manual is classic, as follows:

" Hello World from Lua "  for inch String.gmatch " %a+ "  do    Print (W)    -- continuous output of each word End

8,string.gsub (s, pattern, repl [, n])

This function is used for character substitution. Replaces each matched string with the specified string repl. Returns the number of replaced strings and replacements. Personally think this function is very interesting.

If Repl is a function, the function is called with the matching parameter, and if REPL is table, the matching parameter is used as the key to find the table. As follows:

--stringPrint(string.gsub("i have an apple","Apple","Peach"))--functionfunctionFF (ARG)Print("function arg:".. Arg)EndPrint(string.gsub("My name is Qsk","%a+", FF))--Tablet ={}metat={}metat.__index=function(Table,key)return "!!".. keyEndsetmetatable(t, Metat)Print(string.gsub("My name is Qsk","%a+", T))

When the table is tested, a meta-table is set for the table. The output is as follows:

I have an peach    1function  arg:myfunction  arg:name function Arg:is function arg:qskmy name is Qsk     4 !! My!! Name!! Is!! Qsk    4

Matches a word in a string that matches 4 times so the second parameter of the output is 4.

9,String.len (s), String.Lower (s), String.upper (s)

This two function is too simple, one is to find the length of the string. The other is to convert the string to lowercase. As follows:

Print (string.len("abcd"))        -- 4 Print (string.lower("MACOS"))    -- MacOS Print (string.upper("12abAB"))    -- 12ABAB

10,String.rep (s, n [, Sep])

This function is used to make a string copy itself and link it up. As follows:

Print (string.rep("s"5,"-"))        -- s-s-s-s-s Print (string.rep("ab"5))            -- Ababababab

11,String.reverse (s)

As a name, used to invert a string, reversing the sequence of characters in a string. As follows:

Print (string.reverse("abcdefg"))        -- GFEDCBA

12,string.sub (S, I [, j])

This function is used to intercept strings. Very simple, as follows:

Print (string.sub("abcdefg"3,5))        -- CDE

As we can see, Lua's string handling is really powerful. Strings that are relative to Java add a lot of matching functions that are much easier to use.

One of the more powerful features of the LUA string is the Lua "pattern", which is used for string matching, the specific usage, and referring to the Lua5.3 reference Manual of the Cloud God translation.

Lua's string and string library summary

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.