A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service
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.
- print "Hello, world!"
A more complex example shows what is the Closure ):
- function create_a_counter()
- local count = 0
- return function()
- countcount = count + 1
- return count
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
- While (lua_next (L,-2 )! = 0)
- If (lua_isnumber (L,-1) // you can determine the element type, which may be a string.
- Arrf. add (float) lua_tonumber (L,-1); // obtain the element value
- Lua_remove (L,-1 );
- 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:
- Lua_newtable (L); // create a table and place it on the top of the stack.
- Lua_pushstring (L, "mydata"); // press the key
- Lua_pushnumber (L, 66); // press value
- Lua_settable (L,-3); // the key and value are displayed and set to the table.
- Lua_pushstring (L, "subdata"); // press the key
- Lua_newtable (L); // press value, which is also a table
- Lua_pushstring (L, "mydata"); // press the key of the subtable
- Lua_pushnumber (L, 53); // value
- Lua_settable (L,-3); // the key and value are displayed and set to subtable.
- 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.
- Lua_pushstring (L, "mydata2"); // same as above
- Lua_pushnumber (L, 77 );
- Lua_settable (L,-3 );
- 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)
- //a trick:otherwise the lua engine will crash. This element is invisible in Lua script
- for(int i = 0; i < arri.size();i++)
The resulting array can be traversed in Lua as follows:
- for i,v in ipairs(data.arri) do
- for i=1,table.getn(data.arri) do
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:
- typedef enum
- } BaudRate;
- typedef struct flag
- int onoff;
- int j;
- long l;
- double d;
- char* name;
- BaudRate rate;
The following code is automatically generated:
- bool DataToLua(flag data,lua_State *L)
- 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:
- //function for Lua to call
- //return a integer array to the script
- static int l_getarr (lua_State *L)
- lua_newtable(L);//create table
- lua_pushnumber(L,1);//push the value
- lua_rawseti(L,-2,1);//set t=v
- return 1;
- int main()
- lua_State *L = lua_open(); /* opens Lua */
- luaopen_base(L); /* opens the basic library */
- luaopen_table(L); /* opens the table library */
- luaopen_string(L); /* opens the string lib. */
- luaopen_math(L); /* opens the math lib. */
- lua_pushcfunction(L, l_getarr); // Register a function
- lua_setglobal(L, "getarr");
- if (lua_dofile(L, "testlua.lua"))//Load the script file and Run it
- printf("run script failed\n");
- lua_getglobal(L, "result"); //Get the global variant in Lua script
- printf("The result of the Lua script is %d\n",lua_tonumber(L,-1));
- return 0;
The script code is as follows:
- array = getarr()
- if array ~= nil then
- result = 1
- for i=1,table.getn(array),1 do
- result = 0
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 ).
In VS, select the External Tools under the Tools menu, and configure the following in the displayed dialog box:
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:
- 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.
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.
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.
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.
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.
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.
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.
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.
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!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service