Interaction between Lua and C

Source: Internet
Author: User
  1. Extern "C "{
  2. # Include "Lua. H"
  3. # Include "lualib. H"
  4. # Include "lauxlib. H"
  5. }
  6. # Include <iostream>
  7. # Include <string>
  8. Using namespace STD;
  9. Int main ()
  10. {
  11. // Lua sample code
  12. Char * szlua_code =
  13. "R = string. gsub (c_str, c_mode, c_tag) -- The variable assigned by the host"
  14. "U = string. Upper (r )";
  15. // Lua string Mode
  16. Char * szmode = "(% W +) % S * = % S * (% W + )";
  17. // String to be processed
  18. Char * szstr = "key1 = value1 key2 = value2 ";
  19. // Target string Mode
  20. Char * sztag = "<% 1> % 2 </% 1> ";
  21. Lua_state * l = lual_newstate ();
  22. Lual_openlibs (L );
  23. // Send a piece of data to Lua
  24. Lua_pushstring (L, szmode );
  25. Lua_setglobal (L, "c_mode ");
  26. Lua_pushstring (L, sztag );
  27. Lua_setglobal (L, "c_tag ");
  28. Lua_pushstring (L, szstr );
  29. Lua_setglobal (L, "c_str ");
  30. // Execute
  31. Bool err = lual_loadbuffer (L, szlua_code, strlen (szlua_code ),
  32. "Demo") | lua_pcall (L, 0, 0, 0 );
  33. If (ERR)
  34. {
  35. // If an error occurs, it is displayed
  36. Cerr <lua_tostring (L,-1 );
  37. // The error message at the top of the stack is displayed.
  38. Lua_pop (L, 1 );
  39. }
  40. Else
  41. {
  42. // Obtain the global variable value after Lua is executed
  43. Lua_getglobal (L, "R ");
  44. Cout <"r =" <lua_tostring (L,-1) <Endl;
  45. Lua_pop (L, 1 );
  46. Lua_getglobal (L, "U ");
  47. Cout <"u =" <lua_tostring (L,-1) <Endl;
  48. Lua_pop (L, 1 );
  49. }
  50. Lua_close (L );
  51. Return 0;
  52. }

This code converts all the key = value strings in the string to the XML format <key> value </key>
In this example, the C ++ program pushes the C string to the top of the stack by calling lua_pushstring. The function of lua_setglobal is to upload the data on the top of the stack to the Lua environment as a global variable.
After the code is executed, use lua_getglobal to obtain global variables from the Lua environment and press them to the top of the stack. Then, use lua_tostring to convert the data on the top of the stack to a string. Because lua_tostring itself does not have the stack function, in order to balance (that is, the data volume in the stack before and after the call remains unchanged), lua_pop is used to pop up the data pushed by lua_setglobal.
From the above example, we can see that C ++ and Lua are always turning around the stack, which is very important. It is necessary to list some Major Stack operations in Lua C APIs. Their functions can be seen directly from the function name.
Push elements into the stack

void lua_pushnil (lua_State *L);    void lua_pushboolean (lua_State *L, int bool);void lua_pushnumber (lua_State *L, double n);void lua_pushlstring (lua_State *L, const char *s, size_t length);void lua_pushstring (lua_State *L, const char *s);void lua_pushcfunction (lua_State *L, lua_CFunction fn);

Query the elements in the stack

lua_isnil (lua_State *L, int index);lua_isboolean (lua_State *L, int index);int lua_isnumber (lua_State *L, int index);int lua_isstring (lua_State *L, int index);int lua_isfunction (lua_State *L, int index);int lua_istable (lua_State *L, int index);int lua_isuserdata (lua_State *L, int index);lua_islightuserdata (lua_State *L, int index);lua_isthread (lua_State *L, int index);

 

Elements in the conversion Stack

int                lua_toboolean (lua_State *L, int index);double            lua_tonumber (lua_State *L, int index);const char *    lua_tostring (lua_State *L, int index);const char *    lua_tolstring (lua_State *L, int idx, size_t *len);size_t            lua_strlen (lua_State *L, int index);lua_CFunction   lua_tocfunction (lua_State *L, int idx);void *          lua_touserdata (lua_State *L, int idx);lua_State *     lua_tothread (lua_State *L, int idx);

 

Lua stack Maintenance

Int lua_gettop (lua_state * l); gets the index of the top element of the stack, that is, the number of elements in the stack void lua_settop (lua_state * l, int index); sets the top index of the stack, that is, set the number of elements in the stack. If the index is <0, the number goes down from the top of the stack, the same as void lua_pushvalue (lua_state * l, int index ); copy the elements of the specified index in the stack to the top of the stack void lua_remove (lua_state * l, int index); Delete the element void lua_insert (lua_state * l, int index) of the specified index ); move the top element of the stack to the specified index location, and the number of stacks does not change void lua_replace (lua_state * l, int index ); the element value pops up from the top of the stack and is set to the specified index location. The number of elements in the stack is reduced by one int lua_checkstack. (Lua_state * l, int extra); Ensure that the stack has at least extra space. If the size of the stack cannot be extended, the function returns false. This function will never shrink the stack. Int lua_pop (L, n) pops up n elements from the top of the stack. It is a package of lua_settop: # define lua_pop (L, n) lua_settop (L,-(n) -1)

 

Table operations
The above list does not contain lua_pushtable and lua_totable. How can we obtain or set table data in Lua?
In Lua, table is a very important data type. In a table, not only can a group of data be put like data in C, you can also store data as key = value as map, such as in the Lua code:

TB = {"ABC", 12, true, x = 10, y = 20, Z = 30}

The first three data items can use TB [1] ~ TB [3] acquisition
The last three data items are obtained through TB. X, TB. Y, and TB. Z.
Although it looks like a cool, but it's amazing to peel off. In fact, in the Lua table, all the data is stored in the form of key = value. This Lua code can also be written as follows:

TB = {[1] = "ABC", [2] = 12, [3] = true, ["X"] = 10, ["Y"] = 20, ["Z"] = 30}

It is in the form of [Key] = value, the so-called TB. X is just the syntactic sugar of TB ["X"]. If you want to, you can also use TB ["X"] To get this data 10.
We changed the above example to use the table

  1. ...
  2. Int main ()
  3. {
  4. // Lua sample code, using table
  5. Char * szlua_code =
  6. "X = {} -- table used to store results"
  7. "X [1], X [2] = string. gsub (C. STR, C. mode, C. tag) -- The result in X [1] and the number of replicas in X [2"
  8. "X. U = string. Upper (X [1])";
  9. // Lua string Mode
  10. Char * szmode = "(% W +) % S * = % S * (% W + )";
  11. // String to be processed
  12. Char * szstr = "key1 = value1 key2 = value2 ";
  13. // Target string Mode
  14. Char * sztag = "<% 1> % 2 </% 1> ";
  15. Lua_state * l = lual_newstate ();
  16. Lual_openlibs (L );
  17. // Send a tabele to Lua
  18. Lua_newtable (l); // create a table and press it to the top of the stack.
  19. Lua_pushstring (L, "Mode"); // key
  20. Lua_pushstring (L, szmode); // Value
  21. // Set newtable [mode] = szmode
  22. // Because of the two previous stacks, the table element is now placed at the third position on the top of the stack.
  23. Lua_settable (L,-3 );
  24. // Lua_settable pops up the key and Value
  25. Lua_pushstring (L, "tag"); // key
  26. Lua_pushstring (L, sztag); // Value
  27. Lua_settable (L,-3); // set newtable [tag] = sztag
  28. Lua_pushstring (L, "str"); // key
  29. Lua_pushstring (L, szstr); // Value
  30. Lua_settable (L,-3); // set newtable [STR] = szstr
  31. Lua_setglobal (L, "C"); // set the top element of the stack (newtable) to the global variable C in Lua.
  32. // Execute
  33. Bool err = lual_loadbuffer (L, szlua_code, strlen (szlua_code ),
  34. "Demo") | lua_pcall (L, 0, 0, 0 );
  35. If (ERR)
  36. {
  37. // If an error occurs, it is displayed
  38. Cerr <lua_tostring (L,-1 );
  39. // The error message at the top of the stack is displayed.
  40. Lua_pop (L, 1 );
  41. }
  42. Else
  43. {
  44. // Obtain the global variable value after Lua is executed
  45. Lua_getglobal (L, "x ");
  46. // This X should be a table
  47. If (lua_istable (L,-1 ))
  48. {
  49. // Obtain X. U, that is, X ["U"]
  50. Lua_pushstring (L, "U"); // key
  51. // Due to this stack pressure, X is in the second position at the top of the stack
  52. Lua_gettable (L,-2 );
  53. // Lua_gettable will pop up the key pushed above, and then press the corresponding value
  54. // Obtain the data, and then the value pops up from the stack.
  55. Cout <"x. U =" <lua_tostring (L,-1) <Endl;
  56. Lua_pop (L, 1 );
  57. // Obtain X [1] and X [2]
  58. For (INT I = 1; I <= 2; I ++)
  59. {
  60. // Except that the key is a number, it is no different from the above.
  61. Lua_pushnumber (L, I );
  62. Lua_gettable (L,-2 );
  63. Cout <"X [" <I <"] =" <lua_tostring (L,-1) <Endl;
  64. Lua_pop (L, 1 );
  65. }
  66. }
  67. // The top X of the stack is displayed.
  68. Lua_pop (L, 1 );
  69. }
  70. Lua_close (L );
  71. Return 0;
  72. }

The new Lua c api used in this example is:

Void lua_newtable (lua_state * l); Create an empty table and press it to the top of the stack. Void lua_settable (lua_state * l, int idx); lua_settable uses the index of the table in the stack as the parameter, and outputs the key and value at the top of the stack to the stack and modifies the table with these two values. Void lua_gettable (lua_state * l, int idx); lua_gettable uses the index of the table in the stack as the parameter, and the element at the top of the stack is displayed as the key. The value corresponding to the key is returned and pushed to the top of the stack. Finally, Lua provides the access function void lua_rawgeti (lua_state * l, int idx, int N) for the table to get table [N] and put it on the top of the stack, in the preceding example, the lua_pushnumber (L, I); lua_gettable (L,-2) of lines 69-70 can be replaced by lua_rawgeti (L,-1. Lua_getfield (lua_state * l, int idx, const char * k) to get table. K and put it on the top of the stack. In the above example, the lua_pushstring (L, "U"); lua_gettable (L,-2); can be replaced with lua_getfield (L,-1, "U "). Void lua_setfield (lua_state * l, int idx, const char * k) puts the data at the top of the stack as value into table. in K, the shape in the above example is lua_pushstring (L, "key"); lua_pushstring (L, value); lua_settable (L,-3); you can change it to lua_pushstring (L, value ); the format of lua_setfield (L,-2, "key. Void lua_rawseti (lua_state * l, int idx, int N) puts the data at the top of the stack as value in table [N]

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.