Essential for beginners: quick learning notes for LUA beginners

Source: Internet
Author: User
Tags wxwidgets

LUAThe programming language is a simple, lightweight, and scalable scripting language.LUARead as/'lua/Rue), which is the meaning of "Luna" Moon in Portuguese.

LUAThe goal is to become a language that is easy to embed into other languages. Most programmers also think that it does. Many applications use LUA as their embedded scripting language to achieve configurability and scalability. These include the legend of xianjing, World of Warcraft, the gate of bode.com, And the legend of xuanjicang.

LuaIs a lightweight language. Its official version only includes a streamlined core and the most basic library. This makes Lua small in size and fast in startup. It is written in the Standard C language and open in the form of source code. After compilation, it is only one hundred kb and can be easily embedded into other programs. Unlike many "Big and comprehensive" languages, network communication and graphical interfaces are not provided by default. However, Lua can be easily extended: these functions are provided by the host language (usually C or C ++), and Lua can use them, just as they are originally built in. In fact, many mature extension modules are available.

Lua scripts can be easily called by C/C ++ code, or call C/C ++ functions in turn, which makes Lua widely used in applications. Not only as an extension script, but also as a common configuration file, instead of XML, Ini and other file formats, and easier to understand and maintain. Lua is compiled by standard C. The code is concise and elegant, and can be compiled and run on almost all operating systems and platforms. A complete Lua interpreter is only 200 k. Currently, Lua is the fastest in all script engines. All of these determine that Lua is the best choice for embedded scripts.

Lua has a JIT project at the same time to provide real-time compilation functions on a specific platform, which will bring Lua better performance. Please visit http://luajit.luaforge.net/to learn about this project. Unlike scripts such as Python, Lua does not provide a powerful library, which is determined by its positioning. Therefore, Lua is not suitable for developing independent applications. However, Lua still has basic functions such as mathematical operations and string processing.

Lua is a programming language with Multiple Programming paradigms: it only provides a small set of features to meet the needs of different programming paradigms, instead of providing complex feature support for a specific programming paradigm. For example, Lua does not provide inheritance for this feature, but you can use a meta table to simulate it. Concepts such as namespaces and classes are not implemented in the basic features of languages, but we can easily use the unique complex data structure provided by the table structure Lua.

Lua can construct a function at any time during runtime and regard it as an object called the first class function. This feature can well meet the needs of functional programming. This provides these basic meta-features, and we can modify the language as needed.

Lua's native supports very few data types. It only provides the default double-precision floating point number (configurable), Boolean, String, table, function, coroutine) and user-defined data. However, the processing efficiency of tables and strings is very high. With the support of meta-tables, we can efficiently simulate complex data types, such as collections and arrays ).

Lua is a dynamic language that supports incremental garbage collection policies. Supports collaborative multi-thread corouine that is not related to the built-in operating system.

Sample Code

 
 
  1. print "Hello, world!" 

A more complex example shows what is the Closure ):

 
 
  1. function create_a_counter()  
  2.     local count = 0 
  3.     return function()  
  4.         countcount = count + 1  
  5.         return count  
  6.     end  
  7. end 

Create_a_counter () returns a counter. Each time you call this counter, a value greater than 1 is returned.

Lua Embedded C

The Lua and C Programs exchange data through a stack: struct lua_State

The stack sequence number can be counted from the top and bottom of the stack, from the bottom of the stack, then the bottom of the stack is 1, increasing toward the top of the stack. From the top of the stack, the top of the stack is-1, and the direction toward the bottom of the stack is decreasing. It is generally counted from the top of the stack. The default stack size is 20. You can use lua_checkstack to modify the stack. Use lua_gettop to obtain the number of elements in the stack. It does not mean that there is an integer element at the top of the stack. Instead, it calculates the positive index of the top element of the stack in the stack, which is equivalent to the number of elements.

LuaThe stack used to call the C function is temporary and destroyed after the call is completed.

How to obtain parameters from the Lua script from the stack

If you know the name of a global variable in the Lua script, you can use void lua_getglobal (lua_State * L, const char * name ). This function places the value of the Lua variable referred to by name on the top of the stack.

To obtain the parameters used by Lua to call a function in Function C:

First, use lua_gettop to check the number of parameters.

Use the lua_is... class function to detect the parameter type and handle errors.

Use the lua_to... class function to convert the parameter to number or string. (For Lua, only these two simple types are supported)

Lua_tonumber returns double

Lua_tostring returns char *

Use lua_remove to delete elements from the stack

Continue to obtain the next element. Because lua_remove is called every time, the index used for each call of lua_tonumber is fixed to-1, that is, the top of the stack.

If lua_istable is set up, it indicates that the top of the stack is a table. Note that the table cannot be retrieved, and only the elements in the table can be retrieved one by one.

First, press the element name to the top of the stack: lua_pushstring (L, "I"); then you can call it with lua_gettable, and the value will be placed on the top of the stack. At the same time, the name of the pressed element is displayed. In the above method, we can obtain this value. Remember to use lua_remove. If one element of a table is also a table, repeat it. When all the elements of a table are finished, remember that the table is still in the stack and delete it with lua_remove.

If you want to obtain an array (the so-called array is actually the table where the key is a numerical sequence starting from 1 and the value type is the same), you can use lua_next to traverse this array:

First, press lua_pushnil into a null value, and then

 
 
  1. While (lua_next (L,-2 )! = 0)
  2. {
  3. If (lua_isnumber (L,-1) // you can determine the element type, which may be a string.
  4. {
  5. Arrf. add (float) lua_tonumber (L,-1); // obtain the element value
  6. Lua_remove (L,-1 );
  7. }
  8. }
  9. Lua_remove (L,-1); // Delete NIL

How to return data from C to Lua script

Use the lua_push... class function to push data into the stack and return n; To tell Lua to return several values. Lua supports multiple return values, such as x, y = Test (). Lua extracts data from the stack based on n.

If you want to return a table:

 
 
  1. Lua_newtable (L); // create a table and place it on the top of the stack.
  2. Lua_pushstring (L, "mydata"); // press the key
  3. Lua_pushnumber (L, 66); // press value
  4. Lua_settable (L,-3); // the key and value are displayed and set to the table.
  5. Lua_pushstring (L, "subdata"); // press the key
  6. Lua_newtable (L); // press value, which is also a table
  7. Lua_pushstring (L, "mydata"); // press the key of the subtable
  8. Lua_pushnumber (L, 53); // value
  9. Lua_settable (L,-3); // the key and value are displayed and set to subtable.
  10. Lua_settable (L,-3); // at this time, the location of the parent table is-3. The key, value (subtable) is displayed and set it to the table.
  11. Lua_pushstring (L, "mydata2"); // same as above
  12. Lua_pushnumber (L, 77 );
  13. Lua_settable (L,-3 );
  14. Return 1; // a table is now in the stack. All the other tables are popped up.

If you want to return an array, use the following code: (pay attention to the trick comment. I am waiting for the official explanation. After verification, this problem only occurs when the dll method is called in windows. Normal WinCE)

 
 
  1. lua_pushstring(L,"arri");  
  2. lua_newtable(L);  
  3. {  
  4. //a trick:otherwise the lua engine will crash. This element is invisible in Lua script  
  5.  
  6. lua_pushnumber(L,-1);  
  7. lua_rawseti(L,-2,0);  
  8. for(int i = 0; i < arri.size();i++)  
  9. {  
  10. lua_pushnumber(L,arri[i]);  
  11. lua_rawseti(L,-2,i+1);  
  12. }  
  13. }  
  14. lua_settable(L,-3); 

The resulting array can be traversed in Lua as follows:

 
 
  1. for i,v in ipairs(data.arri) do  
  2. print(v)  
  3. end 

Or

 
 
  1. for i=1,table.getn(data.arri) do  
  2. print(data.arri[i])  
  3. end 

Only the array can do this. The Record consisting of name and value cannot, and table. getn is only valid for the array.

Because of the high similarity of the above Code, it is easy to automatically generate the code. For example, according to a struct definition in C:

 
 
  1. typedef enum  
  2. {  
  3. BR_9600,  
  4. BR_4800,  
  5. } BaudRate;  
  6. typedef struct flag  
  7. {  
  8. int onoff;  
  9. int j;  
  10. long l;  
  11. double d;  
  12. char* name;  
  13. BaudRate rate;  
  14. }flag; 

The following code is automatically generated:

 
 
  1. bool DataToLua(flag data,lua_State *L)  
  2. {  
  3. lua_newtable(L);  
  4. lua_pushstring(L,"onoff");  
  5. lua_pushnumber(L,(double)data.onoff);  
  6. lua_settable(L,-3);  
  7. lua_pushstring(L,"j");  
  8. lua_pushnumber(L,(double)data.j);  
  9. lua_settable(L,-3);  
  10. lua_pushstring(L,"l");  
  11. lua_pushnumber(L,(double)data.l);  
  12. lua_settable(L,-3);  
  13. lua_pushstring(L,"d");  
  14. lua_pushnumber(L,(double)data.d);  
  15. lua_settable(L,-3);  
  16. lua_pushstring(L,"name");  
  17. lua_pushstring(L,data.name.c_str());  
  18. lua_settable(L,-3);  
  19. lua_pushstring(L,"rate");  
  20. lua_pushnumber(L,(double)(int)data.rate);  
  21. lua_settable(L,-3);  
  22. return true;  

LuaToData is similar.

If you use the object-oriented method to encapsulate the flag, it is more convenient to convert the DataToLua into a flag class method.

Examples of mutual calls between C and Lua scripts

First, the main program of C initializes the Lua Script Engine and registers some functions for the script to call:

 
 
  1. //function for Lua to call  
  2. //return a integer array to the script  
  3.  
  4. static int l_getarr (lua_State *L)  
  5. {  
  6. lua_newtable(L);//create table  
  7.  
  8. lua_pushnumber(L,1);//push the value  
  9.  
  10. lua_rawseti(L,-2,1);//set t[1]=v  
  11.  
  12. lua_pushnumber(L,2);  
  13. lua_rawseti(L,-2,2);  
  14. lua_pushnumber(L,3);  
  15. lua_rawseti(L,-2,3);  
  16. lua_pushnumber(L,4);  
  17. lua_rawseti(L,-2,4);  
  18. return 1;  
  19. }  
  20. int main()  
  21. {  
  22. lua_State *L = lua_open(); /* opens Lua */  
  23. luaopen_base(L); /* opens the basic library */  
  24. luaopen_table(L); /* opens the table library */  
  25. luaopen_string(L); /* opens the string lib. */  
  26. luaopen_math(L); /* opens the math lib. */  
  27. lua_pushcfunction(L, l_getarr); // Register a function  
  28.  
  29. lua_setglobal(L, "getarr");  
  30. if (lua_dofile(L, "testlua.lua"))//Load the script file and Run it  
  31.  
  32. {  
  33. printf("run script failed\n");  
  34. }  
  35. else  
  36. {  
  37. lua_getglobal(L, "result"); //Get the global variant in Lua script  
  38.  
  39. if(lua_isnumber(L,-1))  
  40. {  
  41. printf("The result of the Lua script is %d\n",lua_tonumber(L,-1));  
  42. }  
  43. }  
  44. lua_close(L);  
  45. return 0;  

The script code is as follows:

 
 
  1. array = getarr()  
  2. if array ~= nil then  
  3. result = 1 
  4. for i=1,table.getn(array),1 do  
  5. print(array[i])  
  6. end  
  7. else  
  8. result = 0 
  9. end 

Establish a Lua environment in Windows VS 2008

1. Download and compile

Download the new Lua at http://www.lua.org/download.html,

Among them, lua-all.tar.gz includes Lua source code and documentation for each version, where Lua-5.1.3 is used.

Unzip the Lua-5.1.3, enter the command prompt, and navigate to the directory.

Here my unzipping directory is as follows: E: \ Lua-5.1.3,

At the command prompt of VS, enter: etc/luavs. bat here is/not \), or Copy luavs. bat file to E: \ Lua-5.1.3 directly run, after compilation will be generated in the src directory: lua51.dll, lua51.lib, lua.exe, and luac.exe file note, install the C ++ feature of VS. Otherwise, the compilation will fail ).

2. Integration

In VS, select the External Tools under the Tools menu, and configure the following in the displayed dialog box:

Note:

1) Title: The description of the menu item displayed under the tool menu.

2) Command: Specifies the Lua interpreter, that is, the directory where the lua.exe Lua51.lib Lua51.dll Luac.exe file is generated. You can also create a Copy file to a new directory.

3) parameter (Arguments): This parameter can be interpreted as "Export lua.exe source.luaplugin", which corresponds to cl.exe source. cpp, for example, E: \ Source \ $ (ItemFileName) $ (ItemExt ). $ (ItemFileName) indicates the file name, and $ (ItemExt) indicates the file extension. The two parameters can be selected by pressing the button: Item File Name and Item Extension ).

4) Initial directory: directory where lua.exe is located. If you select "use output window", the "Output Window" of VS2008 will be used as the result display area.

Now, the configuration is complete. Create a text file in VS and save it as Print. lua. Enter the following statement:

 
 
  1. print( “Hello, Lua!” ) 

Select "Lua interpreter" under the "Tools" menu to display the console, which displays: Hello, Lua!

Of course, you can also configure the environment variables. Then you can directly enter Lua source. lua in the console to execute the script.

Libraries and tools

Compared with Java, Python, and Perl, Lua may not have many open-source tools and libraries, but many of them are excellent. The following resources can be found in.

I. Kepler

Kepler is a simple and lightweight Web development platform (but it does not mean that it can only be used to develop simple applications). It supports writing Web programs with Lua, so it is easy to learn and use, and can be easily applied in some systems with limited resources. Because ansi c andLuaSo it can be transplanted to any platform that supports ansi c.

Kepler consists of multiple Lua extension libraries, including CGILua, LuaSocket, LuaFileSystem, Copas, LuaSQL, LuaLDAP, LuaExpat, LuaXMLRPC, LuaSOAP, LuaZip, and Xavante, they can be roughly divided into two parts: core library and Function Support library. The core is CGILua and LuaSocket, and the latter is responsible for TCP/UDP sockets operations. The former allows you to create dynamic pages and process input data on web forms. Kepler uses the CGILua starter (launcher) to enable the Web server to execute and communicate with CGILua and Web programs. The current version already includes CGILua starters suitable for CGI, FastCGI, Apache, IIS, Tomcat, and Zope.LuaDeveloped Web programs can be freely migrated in these types of servers, as long as the corresponding CGILua starter is installed at the same time.

LuaFileSystem is a supplement to the file read/write function in the standard Lua library. It provides a portable method to access the directory structure and file attributes of the system. Copas is a coroutine-based service scheduler. Xavante is a Web server developed with Lua that supports HTTP 1.1. It directly supports CGILua without a starter.

Other components provide functions such as SQL database access, XML parsing, LDAP, SOAP, XMLRPC, and ZIP file operations. If you only need some of these functions, you can extract related components (and the components on which they depend) for use.

Ii. wxLua

GUI is a field in which developers spend a lot of effort. Therefore, simplifying the compilation of GUI programs has always been the direction of the majority of programmers. With the rise of scripting languages, it is a very valuable attempt to introduce dynamic, flexible, and easy-to-use scripting languages into GUI development. The complex GUI layout requires a large amount of description information. Therefore, compared with other scripts, Lua language, which is suitable for programming and data description, has unique advantages in GUI construction.

WxWidgets is a well-known cross-platform C ++ GUI library. wxLua builds a bridge between Lua and wxWidgets and uses its Lua code to call almost all wxWidgets functions. WxLua basically maps the wxWidgets class system to the Lua (prototype-based) object model, which enables programmers to develop wxLua programs in an object-based or object-oriented style. Writing, running, testing, and modifying a Lua script can be very fast, which undoubtedly greatly improves the development efficiency of GUI programs. Therefore, wxLua is very suitable for the construction of rapid prototypes. In addition, the good portability of Lua itself and wxWidgets makes the Lua GUI program run smoothly on many platforms.

Iii. Pluto

Although tables in Lua can be saved to files in the form of Lua code through the table constructor for persistence, when there is a complex reference relationship between data, in addition, this task becomes quite difficult and cumbersome in special situations such as cyclic reference and shared reference. Pluto persistence library can solve this problem for users. With its help, programmers can save any complex table data to a binary file in special format for future recovery, and the library will automatically process situations such as cyclic references.

In addition to tables, Pluto also supports persistence of functions (closure) and threads, which makes sense. We all know that a basic action in program debugging is to reproduce bugs. However, in many cases, the conditions for generating bugs are very complex and dependent on many factors, it is difficult for developers to accurately build a completely consistent runtime environment. With Pluto's persistence capabilities for functions and threads, we can save the complete runtime environment of the program when a bug occurs, so that we can easily reproduce the bug in the future. Another important application is the preservation of game progress. The running status of the Lua script that implements game logic can be written to the file at any time for future recovery, which makes it very easy to save the game at any time point.

Iv. LuaCOM

LuaCOM is a supportedLuaAn extension library that interacts with component objects that comply with COM specifications (or automation objects. The interaction involves two aspects: first, allow the Lua program to use COM objects. LuaCOM supports dynamic instantiation of COM objects registered in the system registry and dynamic access to running objects. With the help of LuaCOM, calling the COM Object method is like calling a normal Lua function. The access attribute is similar to the field used to access the table, and it is also responsible for the Automation data type andLuaAutomatic conversion of data types. With these features, the Lua program becomes much easier to operate on COM objects. Coupled with the inherent dynamic nature of Lua, this undoubtedly makes it a very flexible component assembly language.

Another aspect of interaction is supportLuaTo implement (automate) component objects and provide them to external customers. LuaCOM supports both in-process and out-of-process components. It provides auxiliary functions to handle registration and Object Instantiation tasks, thus simplifying related work. Because LuaCOM actually constructs a COM Object Based on the Lua table, we can do something very interesting: In the userdata data type (representing the data structure that does not belong to the Lua world) with the support of the dynamic meta mechanism, Lua can access a variety of external data through tables, including C ++ objects, C structures, or CORBA objects; luaCOM can easily wrap the tables representing the data into a COM Object for external use, so that those old applications and libraries can enter the COM world without too much effort.

V. tolua

It is common to directly use C to implement some functions and then import the corresponding functions into Lua. However, although Lua provides APIs for interaction with C language, you must manually perform tedious Lua stack (for data exchange with C) operations, you also need to note that the data types in the two languages are correctly converted. It is no wonder that the use of Lua's c api is just like the use of assembly languages. To reduce the burden on programmers, some C/C ++ Wrapper came into being.

Tolua is not a Wrapper, but it is an Automatic Generator of Wrapper code. It uses a package file to describe the constants, variables, functions, classes, and methods to be imported into the Lua environment, this type of file is written in simplified C ++ header file format. First, let tolua parse the package file to generate the C/C ++ source file containing the corresponding glue code. Compile the generated source file and link it with the target modules that implement the specific functions.

Although tolua automatically generates the glue code, it is not convenient to write a description file. Some other Wrapper libraries use the C ++ template metaprogramming technology to automatically generate appropriate connection code, thus avoiding additional description files, such as the boost library luabind.

6. LuaJIT

Lua is very efficient and runs faster than many other scripts (such as Perl, Python, and Ruby), which has been proven in a third-party independent evaluation. Even so, some people may not be satisfied. They always think "Well, it's not fast enough !". LuaJIT is an attempt to squeeze out a little more speed. It uses JIT compilation technology to compile Lua code to the local machine code and then directly execute it by the CPU. The LuaJIT evaluation report shows that it has a significant acceleration effect in floating point operations, loops, and collaborative process switching. However, if the program relies heavily on functions compiled by C, the running speed will not be improved. Currently, LuaJIT only supports X86 CPUs.

LuaJIT contains a library named Coco, which can be used independently. Coco provides real coroutine capabilities for Function C. You can suspend the coroutine at any point in Function C, and then return it to that point using the coroutine Restoration Operation in the future. In standard Lua, the suspension and restoration of coroutine cannot span the boundaries of C function calls. Coco uses features that depend on specific systems, so pay special attention when Porting Programs.

VII. ChunkSpy

LuaThe Virtual Machine bytecode instruction set is not part of the language definition, so the official documents are not provided. You can certainly obtain information by viewing the source code, but this is inconvenient after all.

ChunkSpy isLuaThe Virtual Machine bytecode reassembler can output a binary Lua code block to a bytecode Assembly file in a variety of formats that are very easy to read (detailed or simple, with or without the source program. It also supports interactive disassembly. You can view the corresponding bytecode command immediately after you have typed a line of code. The author of ChunkSpy wrote A detailed article about Lua5 VM commands, called A No-Frills Introduction to Lua 5 VM Instructions. You can find it on the project homepage. This article has now corrected the latest Lua5.1. In addition, he is also the developer of the Yueliang project, which uses the Lua language itself to implement Lua. From the project name, the author should be a Chinese.

8. Others

Other libraries and tools include LuaEDIT, LuaEclipse, VS '05lualangpack (all of which are IDE or IDE plug-ins), LuaWrapper, CaLua, ECC, CppLua (Wrapper Library ), luaProfiler (performance measurement tool) and so on, readers can find them and other useful resources on lua-user.org and luaforge.net websites.

Summary: required documents for beginners:LUAThe content of quick learning notes for beginners has been introduced. I hope this article will help you!

Related Article

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.