How to integrate Lua script in C ++

Source: Internet
Author: User

LuaPlusLearn how to take notes onC ++IntegrationLuaThe script is the content to be introduced in this article.LuaScriptC ++I am flattered that many friends are interested in packaging and try to use it. As a matter of fact, I have made a lot of defects in packaging and learning. We recommend that you useLuaPlusAsC ++.

LuaPlusYesLuaOfC ++Enhancement, that is,LuaPlusIn itselfLuaSource code. Use itC ++Cooperation is a good choice.

LuaPlus current version: LuaPlus for Lua 5.01 Distribution Build 1080 February 28,200 4 ). You can download to the http://luaplus.org/Site:

 
 
  1. Source code http://wwhiz.com/LuaPlus/LuaPlus50_Build1081.zip)
  2.  
  3. Target code http://wwhiz.com/LuaPlus/LuaPlus50_Build1081_Win32Binaries.zip)

I will explain how to useLuaPlusAnd how to make it easierLuaPlusAndC ++Class cooperation.

1. Call the Lua script

 
 
  1. // Create a Lua interpreter:
  2. LuaStateOwner state;
  3.  
  4. // Execute the Lua script:
  5. State-> DoString ("print ('Hello World \ n ')");
  6. // Load the Lua script file and execute:
  7. State-> DoFile ("C: \ test. lua ");
  8. // Load the compiled Lua script file and execute it:
  9. State-> DoFile ("C: \ test. luac ");
  10.  
  11. 2. Interaction with Lua scripts
  12.  
  13. // Set variables for Lua scripts
  14. State-& gt; GetGlobals (). SetNumber ("myvalue", 123456 );
  15. // Obtain the Lua variable value
  16. Int myvalue = state-> GetGlobal ("myvalue"). GetInteger ();
  17.  
  18. // Call the Lua Function
  19. LuaFunction <int> luaPrint = state-> GetGlobal ("print ");
  20. LuaPrint ("Hello World \ n ");
  21.  
  22. // Let Lua call the C language function
  23. Int add (int a, int B) {return a + B ;}
  24. State-> GetGlobals (). RegisterDirect ("add", add );
  25. State-> DoString ("print (add (3, 4 ))");
  26.  
  27. // Let Lua call C ++ class member functions
  28. Class Test {public: int add (int a, int B) {return a + B ;}};
  29. Test test;
  30. State-> GetGlobals (). RegisterDirect ("add", test, add );
  31. State-> DoString ("print (add (3, 4 ))");

3.LuaUse in scriptC ++Class

This is a little troublesome. However, I wrapped a LuaPlusHelper. h file, which can easily complete this job. Its implementation is also very simple. You can obtain from the source code how to use pure LuaPlus to implement the same function.

However, there is still a restriction that cannot be solved: Virtual member functions cannot be used. However, considering that we only call the C ++ function in Lua, it is not necessary to import C ++ to Lua perfectly. This restriction is completely acceptable.

In addition, class member variables cannot be directly accessed in Lua, and can be accessed through class member functions, such as SetValue/GetValue ).

 
 
  1. // The following is a simple C ++ class:
  2. Class Logger
  3. {
  4. Public:
  5. Void LOGMEMBER (const char * message)
  6. {
  7. Printf ("In member function: % s \ n", message );
  8. }
  9.  
  10. Logger ()
  11. {
  12. Printf ("Constructing (% p)... \ n", this );
  13. V = 10;
  14. }
  15. Virtual ~ Logger ()
  16. {
  17. Printf ("Destructing (% p)... \ n", this );
  18. }
  19.  
  20. Logger (int n)
  21. {
  22. Printf ("-- Constructing [% d] (% p)... \ n", n, this );
  23. }
  24. Logger (Logger * logger)
  25. {
  26. Printf ("-- Constructing [% p] (% p)... \ n", logger, this );
  27. Logger-> LOGMEMBER ("Call From Constructor \ n ");
  28. }
  29. Int SetValue (int val)
  30. {
  31. V = val;
  32. }
  33. Int GetValue ()
  34. {
  35. Return v;
  36. }
  37. Public:
  38. Int v;
  39. };
  40.  
  41. // Import the script to Lua:
  42. LuaClass <Logger> (state)
  43. . Create ("Logger") // defines the constructor Logger: Logger ()
  44. . Create <int> ("Logger2") // defines the constructor Logger: Logger (int)
  45. . Create <Logger *> ("Logger3") // defines the constructor Logger: Logger (Logger *)
  46. . Destroy ("Free") // defines the Destructor Logger ::~ Logger ()
  47. . Destroy ("_ gc") // defines the Destructor Logger ::~ Logger ()
  48. . Def ("lm", & Logger: LOGMEMBER) // defines the member function Logger: LOGMEMBER (const char *)
  49. . Def ("SetValue", & Logger: SetValue)
  50. . Def ("GetValue", & Logger: GetValue );
  51.  
  52. // Use the Logger class in Lua (1 ):
  53. State-> DoString (
  54. "L = Logger ();" // call the constructor Logger: Logger ()
  55. "L. lm ('Hello World 1');" // call the member function Logger: LOGMEMBER (const char *)
  56. "L. Free ();" // call the Destructor Logger ::~ Logger ()
  57. );
  58.  
  59. // Use the Logger class in Lua (2 ):
  60. State-> DoString (
  61. "M = Logger (10);" // call the constructor Logger: Logger (int)
  62. "M. lm ('Hello World 2');" // call the member function Logger: LOGMEMBER (const char *)
  63. "N = Logger (m);" // call the constructor Logger: Logger (Logger *)
  64. "N. lm ('Hello World 3');" // call the member function Logger: LOGMEMBER (const char *)
  65. "M. SetValue (11 );"
  66. "Print (m. GetValue ());"
  67. "M, n = nil, nil;" // m, n will be recycled by Lua's vertex pole to call the destructor
  68. );

4. classify a group of C functions into the Lua module.

 
 
  1. // Like above, I use LuaPlusHelper. h to simplify it:
  2. LuaModule (state, "mymodule ")
  3. . Def ("add", add)
  4. . Def ("add2", test, add );
  5.  
  6. State-> DoString (
  7. "Print (mymodule. add (3, 4 ));"
  8. "Print (mymodule. add2 (3, 4 ));"
  9. );

5. Use the Lua Table data type

 
 
  1. // Create a Table in Lua
  2. LuaObject table = state-> GetGlobals (). CreateTable ("mytable ");
  3. Table. SetInteger ("m", 10 );
  4. Table. SetNumber ("f", 1.99 );
  5. Table. SetString ("s", "Hello World ");
  6. Table. SetWString ("ch", L "hello ");
  7. Table. SetString (1, "What ");
  8.  
  9. // Equivalent:
  10. // Mytable = {m = 10, f = 1.99, s = "Hello World", ch = L "Hello", "What "}
  11.  
  12. // You can also use table as the key and value:
  13. State-> GetGlobals (). CreateTable ("nexttable ")
  14. . SetString (table, "Hello ")
  15. . SetObject ("obj", table );
  16. // Equivalent:
  17. // Nexttable = {mytable = "Hello", obj = mytable}
  18.  
  19. // Obtain the Table content:
  20. LuaObject t2 = state-> GetGlobals ("mytable ");
  21. Int m = t2.GetByName ("m"). GetInteger ();
  22.  
  23. LuaObject t3 = state-> GetGlobals ("nexttable ");
  24. Std: string str = t3.GetByObject (t2). GetString ();

6. traverse the Table

 
 
  1.  LuaStateOwner state;  
  2.  state.DoString( "MyTable = { Hi = 5, Hello = 10, Yo = 6 }" );  
  3.  
  4.  LuaObject obj = state.GetGlobals()[ "MyTable" ];  
  5.  for ( LuaTableIterator it( obj ); it; it.Next() )  
  6.  {  
  7.  const char* key = it.GetKey().GetString();  
  8.  int num = it.GetValue().GetInteger();  
  9.  } 

Summary:LuaPlusLearn how to take notes onC ++IntegrationLuaThe script content 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.