Parse Lua script C ++ package library LuaWrapper

Source: Internet
Author: User

Lua script C ++ package LibraryLuaWrapper is the content to be introduced in this article, mainly to understand and learnLUA scriptApplication aboutC ++ encapsulation LibraryFor more information, see the detailed description.

Why use Lua as a script?

Using Lua as a script is mainly because it is small, small, and fast), and its syntax is relatively simple and clear. However, it is inconvenient to use LuaAPI to integrate the Lua engine into a program-in the words of a netizen, it is "just like using assembly ". Of course, you don't need to work so hard now, because you can use luawrapw.c ++. Using this tool, it is easy to integrate Lua scripts in C ++. Your original C ++ functions and classes can be shared with Lua scripts without any changes.

Next, we will use examples to explain how to use LuaWrapper to integrate Lua scripts into your program.

1. Create Lua Engine

 
 
  1. LuaWraplua; or LuaWrap * lua = newLuaWrap;

Creating a LuaWrap object is to create a Lua script engine. Based on the features of Lua, you can create any number of Lua engines, or even distribute them in different threads.

2. load and execute the script program

You can load the Lua script from the buffer:

 
 
  1. lua.LoadString(  
  2. "print('HelloWorld')"  
  3. ); 

Of course, you can also install the file and execute the Lua script:

 
 
  1. Lua.LoadFile("./test.lua"); 

The Lua script can be the source code or the compiled intermediate code. Maybe you are more interested in the compiled intermediate code-if you don't want to expose the source code to everyone's eyes.

3. Get and set Lua Variables

The ability to obtain and set the content of script variables is a basic function. You can use the GetGlobal and SetGlobal functions to do this:

(1) Get the variable:

 
 
  1. inta=lua.GetGlobal("a");  
  2. LuaTabletable=lua.GetGlobal("t"); 

Here, <> the type is the type of the expected variable.

(2) set variables:

 
 
  1. lua.SetGlobal("a",a);  
  2. lua.SetGlobal("t",table); 

4. Call the Lua Function

With the Call function, you can easily Call the Lua function from your program:

 
 
  1. lua.Call("print","HelloWorld");  
  2. intsum=lua.Call("add",2,3); 

Here, <> the type is the type of the returned value.

5. How can Lua call C ++ functions?

A brilliant place is coming. Suppose there is a function like this:

 
 
  1. intadd(inta,intb)  
  2. {  
  3. returna+b;  

If you want it to be used by Lua, you just need to register it with the Lua engine:

Lua. RegisterFunc ("add", int (int, int), add );

In this way, Lua can be used directly:

Lua script) sum = add (1, 3)

(*) The RegisterFunc function allows you to register the C ++ function to LuaLua script.

The first parameter is the name of the function to be used in Lua.

The second parameter is the prototype of the function in C ++. C ++ allows function overloading. You can use the function prototype to select the function to be registered to Lua engine.

The third parameter is the pointer of the function in C ++.

6. How can C ++ classes be used in Lua?

Let's take a look at the following C ++ class:

 
 
  1. classMyArray  
  2. {  
  3. std::vectorarray;  
  4. public:  
  5. voidsetvalue(intindex,doublevalue);  
  6. doublegetvalue(intindex);  
  7. intsize();  
  8. constchar*ToString();  
  9. }; 

You are going to allow Lua to freely access and operate on this class. You only need to add several macro definitions:

 
 
  1. ClassMyArray
  2. {
  3. Std: vectorarray;
  4. Public:
  5. Voidsetvalue (intindex, doublevalue );
  6. Doublegetvalue (intindex );
  7. Intsize ();
  8. Constchar * ToString ();
  9. // It is easy to use a class as a Lua object. You only need to add the following macro definitions.
  10. DEFINE_TYPENAME ("My. array ");
  11. BEGIN_REGLUALIB ("array ")
  12. LUALIB_ITEM_CREATE ("new", MyArray) // create MyArray
  13. LUALIB_ITEM_DESTROY ("del", MyArray) // remove MyArray.
  14. END_REGLUALIB ()
  15. BEGIN_REGLUALIB_MEMBER ()
  16. LUALIB_ITEM_FUNC ("size", int (MyArray *), & MyArray: size)
  17. LUALIB_ITEM_FUNC ("_ getindex", double (MyArray *, int), & MyArray: getvalue)
  18. LUALIB_ITEM_FUNC ("_ newindex", void (MyArray *, int, double), & MyArray: setvalue)
  19. LUALIB_ITEM_FUNC ("_ tostring", constchar * (MyArray *), & MyArray: ToString)
  20. LUALIB_ITEM_DESTROY ("_ gc", MyArray) // eliminates objects during garbage collection.
  21. END_REGLUALIB_MEMBER ()
  22. };

With these macro definitions, this class is the class that can be used in Lua, And we can register this class in Lua:

 
 
  1. lua.Register() 

After registration, we can use this class in Lua:

A = array. new () -- creates an object, which is equivalent to a = newMyarray

A [1] = 10 -- call _ newindex, that is, a-> setvalue () in C ++)

A [2] = 20 -- call _ newindex, that is, a-> setvalue () in C ++)

 
 
  1. print( 

A, -- call _ tostring, that is, a-> ToString () in C ++ ()

A: size (), -- equivalent to a-> size () in C ++ ()

A [1], -- call _ getindex, that is, a-> getvalue (1) in C ++)

A [2]) -- call _ getindex, that is, a-> getvalue (2) in C ++)

Array. del (a) -- clears the object, which is equivalent to deletea

A = nil -- clear a, like a = NULL in C ++

Of course, you can also wait for Lua to automatically recycle garbage instead of del. When Lua recycles garbage, it automatically calls the _ gc of this object, which is equivalent to delete.

So what should I do if I want to create a MyArray object in C ++ and pass it to the Lua global variable? As mentioned earlier, SetGlobal is used:

 
 
  1. MyArray*a=newMyArray;  
  2. lua.SetGlobal("a",a); 

To obtain this object, use GetGlobal:

 
 
  1. MyArray*a=lua.GetGlobal("a"); 

For objects passed to Lua, it is better for Lua to manage the lifecycle of the object. If you want to delete it, you can use DelGlobalObject:

 
 
  1. lua.DelGlobalObject("a"); 

However, you should understand what you are doing, because the Lua script may have referenced this object in multiple places. If one of the referenced objects is deleted, other referenced objects may become invalid and the system may crash.

(1)

 
 
  1. DEFINE_TYPENAME("My.array"); 

Name of the definition type. In Lua, this type name is unique for identifying the C ++ type. You must give different names to different objects.

(2)

 
 
  1. BEGIN_REGLUALIB("array")...END_REGLUALIB() 

You can define a library for an object. "array" is the library name. The function defined in the library is a global function. To use this function in Lua, you must add the library name before the function, such as array. new ). Generally, the library contains methods for creating objects. For example:

 
 
  1. LUALIB_ITEM_CREATE ("new", MyArray) // create MyArray

In this way, you can create a MyArray in Lua:

 
 
  1. a=array.new() 

You can also add a delete object operation:

 
 
  1. LUALIB_ITEM_DESTROY ("del", MyArray) // Delete MyArray

In this way, you can directly delete an object:

 
 
  1. array.del(a) 

(3) BEGIN_REGLUALIB_MEMBER ()... END_REGLUALIB_MEMBER ()

Here, you can define the member functions of an object, or overload the object operator-Yes, just like the operator overload of C ++. For example:

LUALIB_ITEM_FUNC ("_ newindex", void (MyArray *, int, double), & MyArray: setvalue)

It is to overload the operator [] operator. There are many operators that can be overloaded in Lua, such:

_ Getindex: operator []. Read access is supported, for example, v = a [10].

_ Newindex: operator []. Value assignment access is supported, for example, a [10] = 1.22.

_ Tostring: convert a variable to a string _ add: equivalent to operator +

_ Add: Operator +

_ Sub: Operator-

_ Mul: Operator ×

_ Div: Operator 'struct'

_ Pow: operator ^ (multiplication)

_ Unm: unary operator-

_ Concat: Operator... (string join)

_ Eq: Operator = (~ = B is equivalent to nota = B)

_ Lt: Operator <(a> B is equivalent to B

_ Le: Operator <= (a> = B is equivalent to B <= a. Note that if "_ le" is not defined ", then Lua will try to convert a <= B to not (B

_ Gc: This function is called during garbage collection, which is equivalent to a C ++ destructor. We strongly recommend that you define this operator to avoid Memory leakage. For example:

LUALIB_ITEM_DESTROY ("_ gc", MyArray) // eliminates objects during garbage collection.

Note: In lua, the access index operator is _ index, not _ getindex. In the luaWrapper library, for ease of use, map it to _ getindex. At the same time, the definition of _ index will be ignored.

That's simple. If you already have a ready-made class and you have no right to modify it, how can you add it to Lua? The answer is to inherit it and add the derived class to Lua.

LuaWrapper needs to use boost library support: boost/type_traits.hpp, boost/function. hpp, boost/bind. hpp, which usesC ++Therefore, if the C ++ compiler does not support this feature, compilation will fail. Currently, many compilers support this feature. In the Visual Studio product series, only VC7.1 supports this feature. Therefore, if you are using Visual Studio, make sure that you are using Visual Studio.

If you think luawrapw.c ++ can help you, I will feel very honored. I would like to share this library with you. By the way, if you find bugs or have good suggestions during use, please contact me. During use, do not delete the signature information in the file. If you have modified the library, add your modification instructions to the modified file. Of course, I would like to welcome you to give back the modified program to me. I will continue to optimize and improve it.

 
 
  1. Attachment testlua.zip]:
  2. Http://blog.blogchina.com/upload/2005-03-18/2005031817460770909.zip
  3. Attachment: luawrapper.zip]:
  4. Http://blog.blogchina.com/upload/2005-03-18/20050318174410511476.zip

Summary: AnalysisLua script C ++ package LibraryLuaWrapper has been introduced.Lua scriptApplicationC ++ encapsulation LibraryContent learning can 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.