Integrate Lua scripts in C ++

Source: Internet
Author: User

Why use Lua as a script?

Using Lua as a script is mainly because it is small (small, 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 luawrapper for 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

Luawrap Lua; or luawrap * Lua = new luawrap;

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:

   lua.LoadString(  "print('Hello World')"  );

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

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 variable:

   int a = lua.GetGlobal("a");  LuaTable table = lua.GetGlobal("t");

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

(2 )?? Set variables:

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

4. Call the Lua Function

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

   lua.Call("print", "Hello World");  int sum = 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:

   int add(int a, int b)  {  return a + 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 Lua for use by the Lua 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:

   class MyArray  {  std::vector array;  public:  void setvalue(int index, double value);  double getvalue(int index);  int size();  const char* ToString();  };

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

 Class myarray {STD: Vector Array; public: void setvalue (INT index, double value); double getvalue (INT index); int size (); const char * tostring (); // It is easy to use a class as a Lua object. You only need to add the following macro definitions. Define_typename ("My. array"); begin_reglualib ("array") lualib_item_create ("new", myarray )?? // Create myarray? Lualib_item_destroy ("Del", myarray )?? // Eliminate myarray. End_reglualib () Evaluate () lualib_item_func ("size", INT (myarray *), & myarray: Size) lualib_item_func ("_ getindex", double (myarray *, INT ), & myarray: getvalue )?? Lualib_item_func ("_ newindex", void (myarray *, Int, double), & myarray: setvalue) lualib_item_func ("_ tostring", const char * (myarray *), & myarray: tostring) lualib_item_destroy ("_ GC", myarray )?? // Eliminate objects during garbage collection. End_reglualib_member ()};

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

Lua. Register ()

After registration, we can use this class in Lua:

A = array. New ()?? -- Create an object, which is equivalent to a = new myarray

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

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

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 ()?? -- Clears the object, which is equivalent to delete

A = nil ?? -- Empty 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:

Myarray * A = new myarray;

Lua. setglobal ("A", );

To obtain this object, use getglobal:

Myarray * A = Lua. getglobal ("");

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:

Lua. delglobalobject ("");

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) 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) 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:

Lualib_item_create ("new", myarray )?? // Create myarray

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

A = array. New ()

You can also add a delete object operation:

Lualib_item_destroy ("Del", myarray )?? // Delete myarray

In this way, you can directly delete an object:

Array. Del ()

(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 not a = 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 )?? // Eliminate 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.

Conclusion

Luawrapper needs boost library support: boost/type_traits.hpp, boost/function. HPP, boost/bind. HPP, which uses the C ++ template for some specific features. Therefore, if the C ++ compiler does not support this feature, it cannot be compiled. 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 luawrapper for 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.

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.