World of Warcraft (4-1)

Source: Internet
Author: User

 

Chapter 2 Use tables 4.1 Use tables to store dataIn Lua, tables are entities used to store other variables (usually these variables are correlated. It is a set of paired elements. Each pair of elements consists of a keyword and a value. In the table, we can use this keyword to obtain the unique value corresponding to it. 4.1.1 Create and index tablesThe following code creates a new table:> Alice ={} in Lua, the expression {} can create a new table, where an empty table is created. Alice is the name of the table. We can use the following statement to assign values to the table:> alice ["name"] = "Alice"> Alice ["phone"] = "13883838438"> Alice ["Address"] = "38 sanba hutong"> Alice ["city ""] =" stormwind "> Alice [" state "] =" FS "every line here tells Lua, you can obtain a value through the keyword in brackets:> Print (Alice ["name"]) Alice> Print (Alice ["Address"]) the keyword in the brackets on the 38 th hutong can be any character except nil (silent speech: tested, Chinese characters can be used, however, because the Lua compiler does not seem to support Chinese characters very well, please try to avoid using it ). In this way, we can also use numbers as keywords:> Alice [1] = "Test Data"> Alice [2] = 12> Print (Alice [1]) test data> Print (Alice [2]) 12 4.1.2 Clear elements from the tableIf you use a keyword that does not exist in the table, the table returns an Nil. Take an example:> Print (Alice ["fax"]) nil, so we can use this to clear the value: simply assign a value to nil.> Alice [1] = nil> Alice [2] = nil> Print (Alice [1]) Nil 4.1.3 String keyword shortcutsIf your keyword is a string rather than a number, Lua provides a simpler method to use it. For example, it was originally written as follows:> alice ["name"] = "Alice" now you can also write:> Alice. name = "Alice" Similarly, you can also use the dot form to access the value in the table:> Print (Alice. name) Alice> Print (Alice. address) No. 38, 38. But compared to the brackets without any naming requirements, this form of vertex requires the naming of keywords. They must begin with letters or underscores, the entire keyword can only contain letters, numbers, and underscores. The reserved key characters (such as for, do, and end) of Lua cannot be used. So Alice ["name"] is correct, but Alice. Name is incorrect. 4.1.4 Create a table with contentThe method described above for creating a table with no content, and then giving it a key-value pair is shown in the actual usage. You will certainly like it in the following form:> alice = {> ["name"] = "Alice",> ["Address"] = "38. 38. hutong",> ["state"] = "FS", >>} similar to the point reference method mentioned above, the Code above can be simpler (speak silently: of course, naming is required.)> Alice ={>> name = "Alice", >>> address = "38 sanba hutong", >>} note the similarities and differences between the two syntax formats. The same point is that each key-value pair is separated by a comma. The last key-value pair can be a comma or not, it is convenient to add a new key-value pair in the future. The difference is that you need to enclose the brackets and double quotation marks, and you do not need to enclose the brackets or double quotation marks. 4.2 Use a table as an arrayIn fact, if you have learned other programming languages, you should feel at the beginning. When a table in Lua uses numbers as keywords, It is very similar to arrays in many other programming languages. Lua calls a table that uses continuous integers starting from 1 as the keyword as an array. 4.2.1 Create an arrayYou can create an array like this: array1 = {value 1, value 2, value 3 ,......} You can also create an array like this: array1 = {[1] = value 1, [2] = value 2, [3] = value 3 ,......} Therefore, arrays are a special form of tables. 4.2.2 Returns the length of an array.Chapter 2nd describes an identifier (#) used to obtain the length of a string. This symbol is also applicable to Arrays:> TBL = {"A", "B ", "C"}> Print (# TBL) 3. the maximum use of this length is that it can provide a dynamic Subscript:> for I = 1, # TBL do> Print (TBL [I])> endabc speak silently: # is restricted here. That is to say, this table is disguised as an array, its subscript must start from 1 and be continuous. In this way, the # length is reliable. 4.2.3 Add elements to an arrayAdding Elements to an array can be written as follows:> TBL [# TBL + 1] = "A", but such code is hard to understand. Therefore, Lua provides a standard table. the insert () function makes adding array elements easy to understand. Table. the syntax of insert () is: Table. the insert (array, [subscript,] value) parameter has the following meanings: L Array -- returns the array L subscript of the added element -- position of the added element L value -- the second parameter of the element value is enclosed in brackets, this parameter can be omitted. If you omit it, the value will be added to the end of the array. Let's take a specific example. First, let's make some preparations and declare an array, which includes three default strings:> TMP = {"apple", "banana ", "Li"} since we will repeatedly display all the content in this array, we define a function to display all the content in an array:> print_tmp = function ()> for I = 1, # TMP do> Print (I, TMP [I])> end first displays the current content:> after print_tmp () 1 Apple 2 banana 3 pear, we call table. insert (). Try adding two more fruits to this array.> Table. insert (TMP, "Mango")> table. insert (TMP, "orange")> print_tmp () 1 Apple 2 banana 3 pear 4 mango 5 orange as we can see, we use the form of omitting the second parameter, so, the newly added two fruits are placed at the end. Let's try again in the form of three parameters:> table. insert (TMP, 3, "Figs")> print_tmp () 1 Apple 2 bananas 3 Figs 4 pears 5 mango 6 oranges as you can see, Figs appear on the 3 position, other fruits are moved sequentially and numbered again. 4.2.4 Delete an element from an arrayLua provides. insert () functions similar to table. remove () to delete an element. Its syntax is as follows: value = table. remove (array [, subscript]) This function has two parameters: L Array -- the array L subscript of the deleted element -- the location of the deleted element is the same, this subscript can also be omitted, if this parameter is omitted, it indicates that the last element in the array is deleted. This function also returns the value of the deleted element. In the following example, we first use a parameter format:> table. remove (TMP)> print_tmp () 1 Apple 2 bananas 3 figs F4 pear 5 mango we see the last element orange was deleted. Next, try the form of two parameters:> table. remove (TMP, 3)> print_tmp () 1 Apple 2 banana 3 pear 4 mango you can see that the figs are deleted, but the array is adjusted in time, their locations are numbered again. 4.2.5 Sorts elements in an array.If the elements in the array include elements that can be compared, a standard library function table. Sort () can sort them. Its syntax is: Table. sort (array [, sorting rules]) table. the second parameter of sort () is described in Chapter 5th, and the first parameter is the array to be sorted. Let's look at an example. We use Chinese characters in the preceding array, while Lua does not sort Chinese characters according to our understanding (speak silently: generally, we sort the numbers of Chinese pinyin in English or pen-and-painting, but Lua does not use these two methods. It seems that it simply compares the encoding size of Chinese characters. This makes it hard to understand), so we redeclare an array and initialize several English characters in disorder:> TMP = {"B", "C ", "A", "E", "D"} print it first:> print_tmp () 1 B2 C3 A4 E5 D. As you can see, there is no sorting. Now, sort and print:> table. the English characters in the sort (TMP)> print_tmp () 1 A2 B3 C4 D5 e array have been sorted alphabetically. In the entire array, the Positional order of all elements is also adjusted. 4.3 Use tables with namespacesWe have introduced several functions to process Arrays: l table. insert () l table. remove () l table. sort () from the name of this group of functions, we can see a rule: they are all table. this table is called namespace here. The namespace provides a way to manage related functions, which increases our ability to manage a large number of functions. In Lua, this namespace is actually a table, so the above function can also be called in the following form: l table ["insert"] () l table ["Remove"] () l table ["sort"] () Next we will learn how to create a namespace, in other words, how to create our own function library. 4.3.1 Create a util namespaceThere is no difference between creating a namespace and creating a table:> util = {} 4.3.2 Add a function to utilThere are two ways to add a function to a namespace. If your function has been defined, you can directly associate the function with a key. If your function has not been defined, you can assign a function definition to a key. The following is an example: 1. Store existing functionsDo you still remember the temperature conversion function we wrote earlier? If you have disabled the Lua compiler, write it again:> convert_c2f = function (Celsius)> return (Celsius * 1.8) + 32> end, this function already exists in the Lua compiler. Next, assign it to the util namespace:> util. c2f = convert_c2f now, we can use util. the c2f () method calls this function, which has the same effect as using the function name convert_c2f:> Print (util. c2f (0) 32 2. Define new functionsIn fact, you do not need to go around a bend. You can directly assign the function definition to a namespace. The following is the factorial function we have previously written. We assigned a value to the util namespace:> util. factorial = function (Num)> Local Total = 1> for I = 1, num do> total = total * I> end> return total> This method is the most common method for creating a function library. The calling method is as follows:> Print (util. factorial (5) 120

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.