Learn more about Lua
I take notes from the Lua game development practice guide, which mainly records some knowledge points in the book.
1. Functions
A function is the main tool used to divide the game script function. It is a Lua code block called by an identifier (actually a variable) and can execute some processing, return values, or both.
Simple functions are defined as follows:
Function Wow ()
Print ("")
Print (wow, that wasaawesome :)
Print ("")
End
The Function Definition starts with the function keyword, followed by the function name, and then the list of parameters passed to the function. In the above example, no parameter is passed to the function, and we still use () to represent an empty parameter list. The Function Definition ends with the end keyword.
Single Parameter
The following example has only one parameter:
Functionsetname (mystring)
Print ("")
Print ("Your name is:", mystring)
Print (")
End
In this function, the mystring parameter is passed to the function and used in the function. The parameters in the function are local variables and are recycled at the end of the call.
Multiple Parameters
In the following example, multiple parameters can be passed, but they are separated by commas (,). For example:
Functionmyinfo (myname, myage)
Print ("")
Print ("Your name is:", myname)
Print ("your age is:", myage)
Print (")
End
Lua also has a powerful function, that is, the list of parameters with an indefinite length. Use (...) In place of the parameter list, Lua creates a local table named Arg to save the parameters passed during all calls and the number of parameters (obtained through Arg. N ).
Return Value
Using Functions for independent processing, you can return the processing structure to the called script. The function uses the return keyword and keeps up with the value (usually the variable name) to return the result. See the following example:
Functiontimestwo (myvalue)
Myvalue = myvalue * 2
Return myvalue
End
You can use a parameter with the returned function as an expression, for example:
A = 24 + timestwo (12)
Return ()
The function can return multiple results separated by commas. See the following example:
Functionthreedice ()
D1 = math. Random (1, 6)
D2 = math. Random (1, 6)
D3 = math. Random (1, 6)
Mytotal = D1 + D2 + D3
Returnd1, D2, D3, mytotal
End
2. Standard Library
Lua provides a large number of standard function libraries to help you complete complex processing without writing additional code.
2.1. Assert (myvalue )()
The assert function allows you to run the compiled Lua code block like a processing function. Input the variable pointing to the compiled code, and then be executed immediately. You can use the loadstring or LoadFile function to load and compile scripts.
In game development, although LoadFile is not commonly used (because it can be loaded in a simple way), loadstring and assert functions are often used in combination. You can use the code block compiled by the loadstring function to store it in the string, and then use the assert function to execute it.
2.2. dofile (filename)
We have used this function before. Its function is to load and immediately execute the Lua script file. We usually use it to load the file of the defined function for calling. In addition, it can also be used to load data files. See the following example:
Dofile ("scripts/runtime_functions.lua ");
2.3. Math. Floor ()
The floor function is used to round down (there is no floating point number or Integer Concept in Lua). This function only removes the decimal part. If you want to round it to an integer, you can add 0.5 first, then round down. See the following example:
A = 5.125
B = 5.75
A = A plus 0.5
B = B + 0.5
A = math. Floor ()
B = math. Floor (B)
2.4. Math. Random ()
Functions can be seen everywhere during game development. The math. Random () function randomly generates a 0 ~ A pseudo-random number between 1 (similar to other programming languages ). The Lua function can be used to specify the maximum and minimum values, so that numbers in this range can be randomly generated. See the following example:
Mydie = math. Random (1, 6)
When the program starts, it is best to set a unique value for the random number seed to get a better random number.
2.5. Math. Min ()
During Game Development, you often need to determine the maximum or minimum values of a set (for example, the highest attribute of a hero role or the maximum vote ). Math. Min and math and Max functions can provide you with such functions. They can accept several numeric parameters. The math. Min function returns the minimum value and the math. Max function returns the maximum value.
2. string processing
One of the most powerful features of Lua is its character processing capability. Lua provides scalable pattern matching and many practical string processing functions.
2.1. type conversion
In game development, conversion is often required between characters and numbers. To convert a string to a number, you can use the tonumber function, for example:
Mystring = "1234"
Mynumber = tonumber (mystring)
Print (mynumber + 2)
You can use the tostring () function to convert numbers to strings.
Mynumber = 1234;
Mystring = tostring (mynumber)
Print (typr (mystring ))
2.2, String. Char (N1, N2 ,..)
The string. Char function returns the characters corresponding to the input parameter based on ASCII encoding. This function is useful when inserting a line break in the Lua game save file.
2.3, String. Len (mystring)
Generally, it is very useful to know the length of a string. This function can tell you that the message returns the string of the input parameter. For example:
Mystring = "1234"
Print (string. Len (mystring ))
2.4, String. sub (mystring, start, end)
String. The sub function returns the substring of the specified string. The start parameter indicates the start position of the substring and the end parameter indicates the end position of the substring. For example:
Mystring = "Hello word"
Newstring = string. sub (mystring, 1, 5)
Print (newstring)
You can also specify the start parameter as a negative number. In this case, the substring position is calculated from the end of the string. If the strt is-5, the last 5 of the string is returned. For example
Mystring = "Hello World"
Newstring = string. sub (-5, 10)
Print (newstring)
The end parameter can be omitted. At this time, the function returns the substring from start to the end of the string. You can use this method to obtain the suffix beauty of a specified string, for example:
Mystring = "Hello World"
Newstring = string. SBU (mystring,-5)
Print (newstring)
2.5, String. Format ()
The string. Format function allows you to format a specified string. This function is commonly used when outputting a string to the GUI. We can use this function to connect a string (LUA cannot simply connect two strings), for example:
String1 = "hello"
String2 = "world"
For Index = 1, 3 do
String = string. Format ("% S % s", string1, string2)
End
Print (string1)
In the preceding example, the first parameter of the string. Format function is used to specify the string format. Because % s represents a string (% d represents a number), % S % s represents connecting two strings.
Another major purpose of the string. Format function is to format and output complex strings based on parameters.
Myname = "Fred"
Mystr = 16
Mystring = string. Format ("% S % d % s", myname, "S strength is", mystr ,".")
Print (mystring)
5.6, String. Find (sourcestring, findstring)
String. Find this function will find the first position that matches the findstring character in sourcestring. If the target character is found, the start and end positions of the target character are returned. If the target character is not found, Nil is returned. For example:
Mystring = "myname is John Smith"
Sstart, send = string. Find (mystring, "John ")
Print (sstart, send)
5.7 characters and formats
Lua's powerful character processing functions support formatting. The format is a template that allows Lua to filter meaningful results from strings.
Mystring = "the price is $17.50"
Filter = "$ % d. % d"
Print (string. sub (mystring, String. Find (mystring, fliter )))
Use uppercase letters to make special symbols (for example, (). % + _*? [^ $] Can also be used in the format, for example, % Represents the percent sign ).
5.8, String. gsub (sourcestring, pattern, replacementstring)
The string. gsub function returns a string. All characters whose sourcestring meets the pattern format are replaced with the value of the replacementstring parameter.
Mystring = "myname is John simth. My phone is 555-3257"
Newstring = string. gsub (mystring, % d ,"*")
Print (newstring)
5.9, String. gfind (sourcestring, pattern)
The string. gfind function traverses a string and returns this substring once a formatted string is found.
Mystring = "Thisis my rather long string"
Print (mystring)
Counter = 1
Formyword in string, gfind (mystring, "% A +") do
Print (string. fotmat ("word # % d: % s", counter, myword ))
Counter = counter + 1
End
Use the for loop to control the structure of the records source string, % A + matches independent words (useful in parsing data)
6. Table Data Structure
6.1. Table. getn (mytable)
Lua provides many built-in functions to operate tables. First, table. getn () returns the number of elements in the table.
Print (table. getn (mytable ))
Generally, we use table to store game data. A single user does not know the number of elements in the table. With this function, the user can obtain the number of elements and obtain each value in the table. For example:
Forindex = 1, Table. getn (mytable) Do
Print (mytable [Index])
End
Table. Sort (mytable)
This simple function traverses the entire table and rearrange it from small to large.
6.2. Table. insert (mytable, positon, value)
Table. the insert function inserts a new value in Table China. The location parameter is optional. If no value is set, a new value is added to the end of table A. If this value is specified, it is inserted to the specified position.
Table. insert (mttable, 25, "hello ")
6.3. Table. Remove (mytable, positon)
The table. Remove function deletes the specified table and returns an element. If necessary, re-index the table. If no poition value is specified, the last element of the table is deleted by default.
Print (table. Remove (mytable, 15 ))
6.4. pairs ()
The pairs () function can traverse every element in the table.
Myname = {"Fred", "Etel", "Lucy", "Ricky", "rocket", "Betsy "}
Forindex, value in pairs (myname) Do
Print (index, value)
End
Lua Game Development Practice Guide Study Notes 2