Application of Lua in C # project:
Lua is a small scripting language. The author is Brazilian. The language is designed to be embedded into an application and provide flexible scalability and customization for the application. Its home page is www.lua.org.
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.
Using Lua in C # is also very simple.
Luainterface is a library for integration between the Lua language and Microsoft. NET platform's Common Language Runtime (CLR ). lua scripts can use it to instantiate CLR objects, access properties, call methods, and even handle events with Lua functions.
You can download this library from the luainterface website. You can start by referencing luainterface. dll in your project.
The bigtank project is not yet determined whether it is open-source, so I will demonstrate it with my own e-PET program (it also uses Lua, you can find all its source code on the lab page ).
C #:
//... <Br/> /// <summary> <br/> // Lua Virtual Machine <br/> /// </Summary> <br/> Private Static Lua luavm = NULL; <br/> // <summary> <br/> // pet constructor <br/> /// </Summary> <br/> Public PET (petform _ petform, string _ petname, string _ petpath) <br/>{< br/> petstate = new petstate (); <br/> petform = _ petform; <br/> petname = _ petname; <br/> // construct a Lua Virtual Machine to parse pet AI <br/> luavm = new Lua (); <br/> // register the API function provided to pet AI <br/> type tThis = This. getType (); <br/> luavm. registerfunction ("petdo", this, tThis. getmethod ("luapetdo"); <br/> luavm. registerfunction ("petdoframe", this, tThis. getmethod ("luapetdoframe"); <br/> luavm. registerfunction ("Sleep", this, tThis. getmethod ("luasleep"); <br/> // load the aifile <br/> luavm. dofile (system. appdomain. currentdomain. basedirectory + _ petpath + "// AI. lua "); <br/>}
Registerfunction registers a public function in the C # code (the latest version of luainterface supports private) for the Lua script. You do not need to care about the number and type of parameters.
Lua:
PetDo("Sleep");
After dofile is executed, the Lua script is called, and the latter calls the petdo function in C # to complete the specified action.
Appendix: Lua details
From the very beginning, Lua was designed as a lightweight scripting language that facilitates embedding (other applications) and is scalable. Therefore, she has been following simple, compact, portable, and fast principles, the official implementation is fully written in ansi c and can be embedded into the host Program in the form of a C library. Each Lua version maintains the open source code tradition, but the license protocols used by each version are different. Since version 5.0 (the latest version is 5.1), she has adopted the famous mit license agreement. Due to the above features, Lua has been widely used in various fields such as game development, Robot Control, distributed applications, image processing, and bioinformatics. Among them, game development is the most important. Many famous games, such as escape from Monkey Island, World of Warcraft, westward journey, lua is used in combination with the engine to complete data description, configuration management, logic control, and other tasks.
As a process-based Dynamic Language, Lua has the following features:
1. The variable name has no type, and the value has a type. The variable name can be bound to any type of value at runtime;
2. The language only provides a unique data structure called a table. It is similar to a key-value associated array and can use any type of value as the key and value. Provides consistent and table-rich table construction syntax, making Lua suitable for describing complex data;
3. functions are of the first type and support anonymous functions and regular tail recursion (proper tail recursion );
4. lexical scoping and closure are supported );
5. Provides the coroutine mechanism of thread type and structured coroutine to facilitate collaborative multitasking;
6. program text in string format can be compiled during runtime and loaded into virtual machine for execution;
7. The dynamic meta-mechanism (Dynamic meta-Mechanism) is provided through the metadata (metamethod) method, which allows the program to change or expand the internal semantics of the syntax facility as needed;
8. convenient use of tables and dynamic meta mechanisms to implement prototype-based object-oriented models;
9. A complete module mechanism has been provided since version 5.1 to better support the development of large-scale applications;
Lua syntax is similar to Pascal and modula, but it is more concise. All syntax generation rules (ebnf) are only 60. Programmers who are familiar with C and Pascal generally have full control over it in just half an hour. In terms of semantics, Lua is very similar to scheme. They fully share the above 1, 3, 4, and 6 features. The continuation and coroutine of scheme are basically the same, but the degree of freedom is higher. Most notably, both languages provide only one data structure: Lua tables and list of scheme ). Because of this, some people even call Lua "only use table Scheme ".
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 resources described below can be found at http://lua-users.org/wiki/luaaddons, and most of them follow the same license agreement as Lua.
I. Kepler
Kepler is a simple and lightweight web development platform (but this 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 and Lua are used for development, 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. Therefore, web programs developed with Lua can be freely migrated on these types of servers, you only need to install the corresponding cgilua starter 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 service scheduler based on the coroutine. Xavante is a web server developed with Lua that supports HTTP 1.1. It directly supports cgilua without a starter.
Its 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 relevant components (and their dependent components) 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 fully 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 an extension library that supports interaction between Lua and component objects that comply with COM specifications (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, it is also responsible for automatic conversion between Automation Data Types and Lua 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 that Lua can be used to 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 to Lua. However, although Lua provides APIs for interaction with C language, you must manually perform tedious Lua stack (used to exchange data 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
Lua's Virtual Machine bytecode instruction set is not part of the language definition, so no documentation is provided officially. You can certainly obtain information by viewing the source code, but this is inconvenient after all.
Chunkspy is a Lua Virtual Machine bytecode reassembler that can output a binary Lua code block to a bytecode Assembly file in a variety of readable formats (detailed or simple, with or without source programs. 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 the lua-user.org and luaforge.net website.