LUA scripting language entry

xiaoxiao2021-03-31  263

Author: Mu Feng Lua programming initially of: Mu Feng (Second Life members) Copyright reproduced, please indicate the original source In this article, I would like to tell you how to Lua programming. I assume that everyone has learned at least one programming language, such as Basic or C, especially C. Because the maximum use of Lua is used as a script in the host program. Lua's syntax is relatively simple, learning is also labor-saving, but the function is not weak. In Lua, everything is variable, except for the keyword. Remember this sentence. I. First, note that writing a program, always less comments. In Lua, you can use a single line annotation and multi-line comments. In a single line of comments, two consecutive minus "-" indicate the beginning of the comment, continues until the end of the row. It is equivalent to "//" in the C language. In multi-line comments, "- [[[" means comments, and continues until "]]". This annotation is equivalent to "/ * ... * /" in the C language. In the comment, "[[[" and "]]" can be nested. Ii. Lua programming classic "Hello World" program is always used to begin to introduce a language. In Lua, writing a such program is simple: Print ("Hello World") In Lua, can be separated from a semicolon between the statement; ", it is also possible to separate it by blank. In general, if multiple statements are written in the same line, it is recommended to separate with a semicolon. Lua has several program control statements, such as: condition control: IF condition THEN ... ELSEIF Condition THEN ... ELSE ... END While loop: While Condition DO ... END REPEAT loop: REPEAT ... Until Condition for loop: for variable = initial value, end point Value, stepper do ... End for loop: for variable 1, variable 2, ..., variable N IN table or enumeration function DO ... END Note that the loop variable of For is always only acting on the partial variable of for, you can also Omit the input value, this time, the FOR cycle will use 1 as a step value. You can use Break to trouble a loop. If you have the foundation of programming, for example, you have learned Basic, C, you will feel that Lua is not difficult. But there are several places where Lua is clearly different from these programming languages, so please pay special attention. . The block statement block is enclosed in C , in Lua, in Lua, it is enclosed in DO and END. For example: Do Print ("Hello") End You can set part of the local variable in the function. . Assigning statement assignment statements are enhanced in Lua. It can assign multiple variables at the same time. For example: A, B, C, D = 1, 2, 3, 4 even: a, b = b, a - how convenient switched variable function. By default, variables are always considered globally. If you want to define a local variable, you need to use local instructions when you assign a value. For example, Local A, B, C = 1, 2, 3 - A, B, and C are all partial variables. Numerical operations and C language, support , -, *, /.

But Lua has more "^". This represents the index multiplier operation. For example, 2 ^ 3 results are 8, 2 ^ 4 results are 16. Connect two strings, you can use "..". Such as: "THIS A" .. "string." - is equal to "this a string". The comparative operation <> <=> = == ~ = indicate less than, larger, not greater than, not less than, equal, non-equal, all of these operators always returns TRUE or FALSE. For Table, Function, and UserData types, only == and ~ = can be used. Equality indicates that two variables are referenced by the same data. For example: a = {1,2} b = a print (a == b, a ~ = b) - true, false a = {1, 2} b = {1, 2} print (a == B, A ~ = b) - False, True. Logical Operations and, OR, NOT, where and and or C language distinguishes particularly large. Here, please remember, in Lua, only False and NIL are calculated as false, and any other data is calculated as true, 0 is also True! The results of the AND and OR are not TRUE and FALSE, but related to its two operands. A and B: If A is false, return a; otherwise return B A or B: If A is true, return A; otherwise return B to a few examples: Print (4 and 5) -> 5 Print (NIL AND 13) -> NIL Print (false and 13) -> False Print (4 or 5) -> 4 Print (false or 5) -> 5 is a very useful feature in Lua, is also a comparison The characteristics of people mixed. We can simulate the statement in the C language: x = a? B: c, in Lua, you can write: x = a and b or c. The most useful statement is: x = x or v, it is equivalent to: if not x t x = v end. . Operator priority, from high to low order as follows: ^ NOT - (1 yuan calculation) * / - .. (string connection) <> <=> = ~ == oriii. Keyword keyword is not possible For variables. LUA's keywords are not much, as follows: And Break do else Elseif End false for functioniff. You can check it with a Type () function.

The type supported by Lua has the following: nil null value, all the variables that have not been used are NIL. NIL is both a value and a type. Boolean Boolean Number Numerical, in Lua, the value is equivalent to the Double String string of the C language. If you prefer, the string can contain the Table relationship table type of '/ 0' characters, this type of function is more powerful, we are Slowly say later. Function functions, don't doubt, the function is also a type, that is, all functions, it is a variable. Userdata Well, this type is dedicated to dealing with Lua host. The host is usually written in C and C , in which case UserData can be any data type of the host, which is commonly used with struct and pointers. Thread thread type, there is no real thread in Lua. One function can be run into several parts in LUA. If you are interested, you can take a look at Lua's documentation. V. Definition of variables All languages ​​are used to use variables. In Lua, no matter where you use variables, you don't need to declare, and all these variables are always global variables, unless you add "local" in front. This should be paid to it, because you may want to use local variables in the function, but forget to use local to explain. As for the variable name, it is case-sensitive. That is, A and A are two different variables. The method of defining a variable is to assign a value. "=" Operation is to assign us together to define several common type of variable. A. NIL is as mentioned earlier, the value of the variable that has not been used is NIL. Sometimes we also need to remove a variable, this time we can directly assign a NIL value directly. Such as: var1 = nil - Please note that NIL must be lowercase B. Boolean Boolean value is usually used when the condition is determined. There are two of the Boolean values: true and false. In Lua, only False and NIL are calculated as false, and all any other types of values ​​are True. For example, 0, an empty string, etc. are True. Don't be misleaded by C language habits, 0 in Lua is indeed true. You can also give a variable to the value of the Boolean type, such as: varboolean = true C. Number in Lua, there is no integer type, nor is it. In general, as long as the value is not very large (such as no more than 100,000,000,000,000), it does not produce a rounding error. On a lot of CPUs, the implementation of the real number is not slower than the integer. Real representation, similar to C language, such as: 4 0.4 4.57E-3 0.3e12 5e 20 D. String string, always a very common advanced type. In Lua, you can very conveniently define a long string.

String has several methods in Lua to represent that the most common method is to include a string with dual quotation marks or single quotes, such as "this is a string." And C language, it supports some The escape character, the list is as follows: / a Bell / b Back Space / f form feed / n newline / r carriage return / t horizontal tab / v vertical Tab // BACKSLASH / "Double Quote / 'Single Quote / [Left Square Bracket / Right Square Bracket, because this string can only be written in a row, there is inevitable to use escape characters. Join the string of escape characters, it seems to be compliment, such as: "One line / NNEXT line / N / "in quotes /", 'in quotes' "a big" / "symbol makes people look very appetite. If you have the same feelings with me, then we can use another in Lua Method: Use "[[[[[" and "]]" to enclose multi-line characters, such as: Page = [http://www.lua.org "> Lua [[a Text Between Double Brackets]] ]] It is worth noting that in this string, if "[[[[" or "]]" contains "[[[[" or "]]", "/ [" or "/]" is still available to avoid ambiguity. Of course, this situation is rare. E. Table Relational Table Type, this is a very powerful type. We can regard this type as an array. Just the array of C language, you can only use the positive integer to work; in Lua, you can use any type to make an index of the group, except for NIL. Similarly, in the C language, the contents of the array only allow one type; in Lua, you can also use any type of value to make an array of content, except for NIL. Table is very simple, and its main feature is to create a series of data elements with "{" and "}". For example: t1 = {} - Define a blank table T1 [1] = 10 - then we can use it like a C language.

T1 [John "] = {AGE = 27, Gender =" Male "} This sentence is equivalent to: t1 [" john "] = {} - must first be defined as a table, remember that the undefined variable is NIL type T1 [John "] [" AGE "] = 27 T1 [" John "] [" gender "] =" Male "When the table's index is a string, we can abbreviate: t1.john = {} T1.john.age = 27 t1.john.gender = "Male" or t1.john {agn = 27, gender = "Male"} This is a strong feature. At the time of defining a table, we can write all the data content between "{" and "}", which is very convenient, and looks very nice. For example, we can write this: t1 = {10, - equivalent to [1] = 10 [100] = 40, john = - If you are original, you can also write: ["john" ] = {AGE = 27, - If you are original, you can also write: ["agn"] = 27 gender = MALE - If you want, you can write: [""] = Male}, 20 - - It is equivalent to [2] = 20} looks very beautiful, isn't it? When we are writing, you need to pay attention to three points: first, all elements, always use comma "," separated; second, all index values ​​need to be "[" and "]"; if it is String, you can also remove quotation marks and middle brackets; third, if you do not write an index, the index will be considered a number and automatically edited from 1 in order; the structure of the table type is so convenient, so that it is often It is used in place of the configuration file. Yes, don't doubt, it is beautiful than the ini file, and is much more. F. Function functions, in Lua, the definition of functions is also simple. Typical definitions are as follows: Function add (A, b) - add is a function name, A and B are parameter name RETURN A B - RETURN to return the function of the function END, please note that returnography must be written in End prior to. If you have to put a Return in the middle, then write it: do return end. I still remember that the function is also a variable type? The above function definition is actually equivalent to: add = function (a, b) Return A B End When you re-assign a value, it no longer represents this function. You can even assign any data to add, including NIL (this, you will clear the add variable).

Is Function not very like a C language function pointer? As the C language, Lua's function can accept variable parameters, which is also defined by "...", such as: Function SUM (A, B, ...) If you want to get the parameters represented, you can function Access the ARG partial variable (Table type) is obtained. As SUM (1, 2, 3, 4), in the function, a = 1, b = 2, arg = {3, 4} is more valuable, it can return multiple results at the same time, such as Function S ( RETURN 1, 2, 3, 4 End A, B, C, D = S () - At this time, A = 1, B = 2, C = 3, D = 4, said, the table type can have arbitrary Type value, including functions! Therefore, there is a very powerful feature that has a table of functions, oh, I want to be more appropriate to say that it is an object. LUA can be programmed with object-oriented. Do not believe? Then I will use the following: t = {agn = 27 add = function (self, n) self.age = self.age n end} Print (T.AGE) - 27 T.ADD (T, 10) Print . At - 37 However, T. ADD (T, 10) This sentence is a little dirty? It doesn't matter, in Lua, you can abbreviate: T: add (10) - equivalent to T. ADD (T, 10) G. UserData and Thread these two type topics, beyond the content of this article, not planning Apologically said. Vi. Is the concluded words ended? Of course, it is next, you need to use the Lua interpreter to help you understand and practice. This small text only helps you understand the grammar of Lua. If you have a programming basis, I believe it will come up with Lua. Like the C language, Lua provides considerable standard functions to enhance the language of the language. Use these standard functions, you can easily operate various data types and process the input and output. For information on this, you can refer to "Programming in Lua" book, you can watch the electronic version directly on the Internet, the URL is: http://www.lua.org/pil/index.html of course, Lua's most Powerful function is to cooperate with the host program honey, so, next article, I will tell you how to use the Lua language as a script in your program to interact with Lua scripts.

Using procedure 1. Using the function of the function demonstrates how to use functions in Lua, and local variable example E02.lua - functions function pythagorean (a, b) local c2 = a ^ 2 b ^ 2 Return SQRT (C2) End Print (3,4)) Run results 5 Program illustrate the definition format of the function in Lua: Function function name (parameter) ... End is different from the PASCAL language, End does not need to be paired with Begin, only need to function After the end, you can have an end. The function of this example is a known straight triangular right angle, asking the horizontal length. Parameters A, B represent the right angle side length, define the Local variable in the function to store the beveled Square. The same as the C language, the code defined in the function will not be executed directly, only when the main program is called. Local means defining a local variable, if LOCAL just said that C2 is a global variable, Local The role domain is between the prosthetic end and its paired keyword, such as if ... End, while ... End, etc. The role of global variables is the entire program. 2. Cycle word example E03.lua - loops for i = 1,5 do print ("i is now" .. i) END Run Results I is now 1 I is now 2 i is now 3 i is now 4 i is NOW 5 Sample Description This This is evenly used to use the For statement for variable = parameter 1, parameter 2, parameter 3 DO cyclic body End variable will be stepped by parameter 3, and the parameter 1 varies to parameter 2, for example: for i = 1, f (x) Do Print (i) endfor i = 10, 1, -1 do print (i) end Here PRINT ("i is now" .. I), even it is used .., this is used to connect two The string, even if you mention it in (1), you don't know if you have an answer. Although I is an integer amount, Lua will automatically turn into a string type when processing, and do not need to be counted.

3. Conditional branching sentence E04.lua - loops and conditionals for i = 1,5 DOPRINT ("i is now" .. I) IF i <2 Then Print ("small") elseif i <4 kil print ("" Medium ") Else Print (" BIG ") End End Run Results I is now 1 Small I is now 2 Medium I is now 3 Medium I is now 4 BIG I IS NOW 5 BIG program Description If ELSE Usage is simple, similar to C Language, but you need to note here that the entire IF requires only one end, even if multiple Elseif is used, is also an end. For example if OP == " " THEN R = A B elseif OP == "-" THEN R = a - b elseif op == "*" THEN R = a * b elseif op == "/" THEN R = A / B ELSE ERROR ("Invalid Operation") end4. Try to see Lua except for the for loop, Support multiple loops, please use While ... do and repeat ... Until to rewrite the use of the FOR program array in this article 1. Introduction LUA language has only one basic data structure, that is, Table, all other data structures, such as arrays. , Class, can be implemented by table .2.Table Squarium E05.lua - arrays mydata = {} mydata [0] = "foo" mydata [1] = 42 - Hash Tables mydata ["bar" ] = "Baz" - Itereate Through the - structure for key, value in mydata do print (key .. "=" .. value) End output result 0 = foo 1 = 42 bar = baz program description first defines one Table mydata = {}, then the two values ​​are assigned to it with a number. This definition method is similar to the array in C, but is different from the array, each array element does not need to be the same. Type, like one in this example, one is a string. The second part of the program is a string, and an element is added to the table. This Table is very like MAP inside STL. TABLE The subscript can be any basic type supported by Lua. In addition to the NIL value. Lua's processing of Table Table, such as the code A = {} a ["x"] = 10 b = A - `b 'refers to the Same Table as` a' print (b ["x"]) -> 10 b ["x"] = 20 Print (a ["x"]) -> 20 a = nil - - Now Only `b 'Still Refers to the Table B = NIL - NOW There no references LEFT to the TABLEB and A are poked to the same TABLE, only one memory, when executed to a = nil, B still points to TABLE When executed to b = nil, because there is no variable to the Table, Lua will automatically release the TABLE's memory 3.Table Nested table can also be nested,

转载请注明原文地址:https://www.9cbs.com/read-130892.html

New Post(0)