Beginner's starter Lua and C + + call each other (including multiple demos)

Source: Internet
Author: User

In the first two articles, the use of C + + calling Lua in VS2010 compiled lua5.1 source generation Lua.lib and VS projects has been described to ensure that the demo runs on vs. Here is a detailed introduction to the mutual invocation and rationale between C + + and Lua.

The direct call of C + + and Lua actually passes the data through a stack structure, the top index value of the stack structure is-1, the index value to the bottom of the stack is-1, -2 ... the top index of the stack is 1. Stack structure can put functions, tables, strings, shaping and other LUA basic data.

First, create the Test.lua file in the current CPP directory for interactive calls with C + +, with the following code:

Print ("Hello World from Lua file") table1 = {}table1["dinner"] = "Rice" table1["hahha"] = "ri123ce" GSCREENW = 1280;function  Getintegersumfuncs (A, b) <span style= "White-space:pre" ></span>return A + bendavg, sum = Average (10, 20, 30, 40 , 50)

Second, familiar with the C language API commonly used in Lua.

int Lual_dofile (lua_state *l, const char *filename); Run the Lua file, L is the stack structure that is currently created. Returns 0, runs the file normally, returns 1, indicates an exception occurred.

void Lua_setglobal (lua_state *l, const char *name); POPs a value from the stack and sets it to the global variable name

void Lua_getglobal (lua_state *l, const char *name); Pushes the value of the global variable name into the stack with a stack top value of-1.

const char *lua_tostring (lua_state *l, int index); The index value of the stack L is value at index and converted to C string (Lua_tointeger, etc.)

void Lua_settop (lua_state *l, int index);//parameters allow incoming any acceptable index and 0. It will set the stack top to this index. If the new stack top is larger than the original, the new element that is out of the section will be filled with nil. If index is 0, all elements on the stack are removed.

int lua_gettop (lua_state *l);//Returns the number of elements on the stack (returns 0 indicates that the stack is empty)

int Lua_next (lua_state *l, int index); POPs a key (key) from the stack, and then presses the Key-value (healthy value) pair into the stack (the next (next) pair after the specified key) in the table specified by the index. If there are no more elements in the table, then Lua_next returns 0 (nothing is pressed into the stack).

void Lua_pushinteger (lua_state *l, Lua_integer N); Put N as a digital compression stack.

void Lua_close (Lua_state *l);//Destroy all objects in the specified LUA state machine

If you need to query other functions, it is recommended to refer to the LUA 5.1 reference manual, which is very detailed and accurate.

Third, C + + gets the global string in Lua.

Gets the LUA global stringconst char* getluaglobalstring (char *filename, char *varname) {lua_state *l = Lua_open (); Lual_openlibs (L );//load and run the Test.lua file int isOpen = Lual_dofile (L, fileName); if (IsOpen = = 0) {printf ("Error loading Lua");} Sets the index of the top of the stack to that index, and if index passes 0, remove all elements on the stack lua_settop (L, 0); The value in the global variable Allglobalchar is pressed onto the stack. char *allglobalchar = varName; Lua_getglobal (L, Allglobalchar); int statecode = lua_isstring (L, 1); if (statecode! = 1) {printf ("Open Lua error code:%d", statecode); return NULL;} Const char* s = lua_tostring (l, 1);p rintf ("Get global screenw is:%s \ n", s); Lua_pop (L, 1); Lua_close (l); return s;}
Calling code:

Getluaglobalstring ("Test.lua", "Gscreenw");

Iv. C + + Gets the values in LUA table

Const char* getluavaroftable (const char *filename,const char *tablename, const char *keyname) {lua_state *l = Lua_open (); L Ual_openlibs (l); int isOpen = Lual_dofile (L, FileName), if (IsOpen! = 0) {printf ("Error open lua file"); return NULL;} Lua_settop (l, 0);//Empty Stack Lua_getglobal (l, tableName); int statecode = Lua_istable (L,-1);//Take stack top if (statecode! = 1) {printf (" Get table Failed code:%d ", statecode); return NULL;} Lua_pushstring (L, KeyName); Lua_gettable (L,-2); Take stack top next element const char* VALUESTR = lua_tostring (L,-1); Fetch stack top printf ("Get LUA table Key-value%s-%s", KeyName, Valuestr); Lua_pop (L, -1); return valuestr;}
Calling code:

Getluavaroftable ("Test.lua", "Table1", "Dinner");

V. C + + gets the table in Lua
<pre name = "Code" class= "Java" >string getluavartable (const char* fileName, const char *tablename, char *result) {lua_state *l = Lu A_open (); Lual_openlibs (l); int isOpen = Lual_dofile (L, FileName), if (IsOpen! = 0) {printf ("Error open lua file"); return NUL L;} Lua_getglobal (L, tableName); int size = Lua_gettop (l); Lua_pushnil (l); int index = 0;while (Lua_next (l, size)) {Const char* Key = Lua_tostring (L,-2);//Take a stack top next element const char* value = lua_tostring (l,-1); Take stack top//Use memcpy, index record address cursor memcpy (&result[index], key, strlen (key)), Index + = strlen (key),//Because sizeof takes a string, there will be "/ 0 "occupies one byte, so should subtract 1memcpy (&result[index],"-", sizeof ("-")-1); Index + = 1;memcpy (&result[index], value, strlen ( value); index + = strlen (value); Lua_pop (L, 1);} Result[index] = 0;cout << "result is" << result << endl;//free (result);//PRINTF ("---%s", result.c_str) ; Lua_pop (L, 1); return result;} 
Calling code:

char* Reslut = (char*) malloc ((char)), getluavartable ("Test.lua", "table1", Reslut); free (reslut);

Six, CPP calls the functions in Lua

To invoke a function, follow the following protocol: first, the function to be called should be pressed into the stack;//Next, the parameters that need to be passed to the function are pressed in the positive sequence; This means that the first parameter is stacked first. Finally call Lua_call; Nargs is the number of arguments you press into the stack. When the function call is complete, all arguments and the function itself will be stacked. The return value of the function is then pressed into the stack. The number of return values will be adjusted to Nresults unless Nresults is set to Lua_multret. In this case, all the return values are pressed into the stack. Lua guarantees that the return value is placed in the stack space. The return value of the function will be stacked on a positive sequence (the first return value is stacked first), so the last return value will be placed at the top of the stack after the call ends. Const char* Callluafunc (const char* fileName, const char* functionname) {lua_state *l = Lua_open (); Lual_openlibs (L); int is  Open = Lual_dofile (l, filename), if (IsOpen! = 0) {printf ("Error open Lua file%s", fileName); return NULL;} lua_getglobal (L , functionname);//What happens if the table and function have the same name Lua_pushinteger (L, 3);//First parameter: Number of functions The second argument: the number of return values of the function Lua_call (l , 2, 1); int result = Lua_tointeger (L, -1);p rintf ("Call Lua func Result:%d", result); return NULL;}
Calling code:

Callluafunc ("Test.lua", "Getintegersumfuncs");

VII. LUA calls the CPP function to calculate the average

CPP computes the average of the function int average (lua_state* l) {int n = lua_gettop (l);d ouble sum = 0;int i;for (i = 1; I <= n; i + +) {if (!lua_i Snumber (L, i)) {lua_pushstring (L, "incorrect argument to avg"); Lua_error (l);} Sum + = Lua_tonumber (L, i);} Lua_pushnumber (L, sum/n); Lua_pushnumber (l, sum);//The number of elements must be returned here, if return 0 will not find the result of return 2;} LUA calls CPP to calculate the mean, call entry int averagemain () {lua_state* L = lua_open (); Lual_openlibs (L);//register LUA function, actually average push to stack structure, The set average function is then the global function Lua_register (L, "average", average);//Run Script Lual_dofile (L, "Test.lua");//Push the value of the global variable avg into the stack Lua_ Getglobal (L, "avg");//Stack top is-1, bottom 1cout << "cpp Show:avg is" << Lua_tointeger (L, -1) <<endl;//pops an element from the stack/ /lua_pop (L, 1);//The value of the global variable sum is pressed into the stack lua_getglobal (l, "sum"); cout << "cpp show:sum is" << Lua_tointeger (L,-1) <<endl;//Clear Stack structure lua_close (L); return 0;}
Code calls:
Averagemain ();


These are the usual demos for C + + and LUA calls.

Attached here is a project example: http://download.csdn.net/detail/wangbin_jxust/7809743

If you need to run the project, you need to use VS2010 compiled lua5.1 source code generation Lua.lib configuration again, and then run.








Beginner's starter Lua and C + + call each other (including multiple demos)

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.