Lua and C + + interaction detailed Summary _4_lua call C + +

Source: Internet
Author: User

Iv. Lua calls C + +

We implement it in three ways.

Method One: Write the module directly into the LUA source code

In Lua, we can write a function in LUA.C and then recompile the LUA file.

After compiling it, it's like this: ()


Then we can add our own functions to the LUA.C. The function to follow the specification (which can be viewed in lua.h) is as follows:

typedef int (*lua_cfunction) (Lua_state *l);
In other words, all functions must receive a lua_state as an argument and return an integer value. Because this function uses the LUA stack as a parameter, it can read any number and any type of arguments from the stack. The return value of this function indicates how much of the return value is pressed into the LUA stack when the function returns. (because LUA functions are capable of returning multiple values)
We then add the following function to the LUA.C:

This is my function  static int gettwovar (lua_state *l)  {      //pushes 2 values into the function stack      lua_pushnumber (L, x);      Lua_pushstring (L, "Hello");         return 2;  }   In the Pmain function, add the following code after the Lual_openlibs function://Register function  lua_pushcfunction (l, Gettwovar);//Put functions in the stack  lua_setglobal (L, " Gettwovar ");   Set LUA global Variables Gettwovar
by finding Lua.h

/#define Lua_register (L,N,F) (Lua_pushcfunction (L, (f)), Lua_setglobal (L, (n)))
we found that the previous registration function can be written like this:
Lua_register (L, "Gettwovar", Gettwovar);
Run, results


Of course, in general, we do not recommend to modify other people's code, more inclined to write their own independent C + + module for the LUA call, the following is how to implement.

Method Two: Use a static dependency method

1. Create a new empty Win32 console project, remember that in the VC + + directory, the header files in Lua and the directory of LIB files are included, and then the linker-and additional dependencies, including Lua51.lib and Lua5.1.lib.

2. Create a new Avg.lua under the directory as follows:

AVG, sum = average ("The  average is", avg) print (  "The sum is", sum)
3. The new test.cpp is as follows:

 #include <stdio.h> extern "C" {#include "lua.h" #include "lualib.h" #include "lauxlib.h"}/* pointer to the LUA interpreter */lua_s  Tate* L;      static int average (lua_state *l) {/* Gets the number of arguments */int n = lua_gettop (L);      Double sum = 0;         int i;      /* loop to find the sum of the parameters */for (i = 1; I <= n; i++) {/* summation */sum + = Lua_tonumber (L, i);      }/* Press-in average */Lua_pushnumber (L, sum/n);      /* Press in and */Lua_pushnumber (L, sum);  /* Returns the number of return values */return 2;         } int main (int argc, char *argv[]) {/* Initialize LUA */L = Lua_open ();      /* load into LUA basic library */Lual_openlibs (L);      /* Registration function */lua_register (L, "average", average);      /* Run the script */lual_dofile (L, "Avg.lua");         /* Clear LUA */lua_close (L);      /* Pause */printf ("Press ENTER to exit ...");      GetChar ();  return 0; }
To execute, we can get the result:

The approximate order is that we write a module function in C + +, register the function in the LUA interpreter, then execute our LUA file by C + + and invoke the function that we just registered in Lua.

It looks awkward, and there's wood. The next step is to describe how the DLL is called.

Method Three: How to use DLL dynamic link

Let's start with a new DLL project named Mlualib. (so the last DLL exported is also MLualib.dll)

Then write our C + + module, take the function as an example, we will first create a new. h file and a. cpp file.

h files are as follows:

#pragma once  extern "C" {  #include "lua.h"  #include "lualib.h"  #include "lauxlib.h"  }     #ifdef Lua_exports  #define LUA_API __declspec (dllexport)  #else  #define LUA_API __declspec (dllimport)  # endif     extern "C" Lua_api int luaopen_mlualib (lua_state *l);//define Export function
The . cpp files are as follows:

 #include      <stdio.h> #include "mLualib.h" static int averagefunc (lua_state *l) {int n = lua_gettop (L);      Double sum = 0;         int i;         /* loop to find the sum of the parameters */for (i = 1; I <= N; i++) sums + = Lua_tonumber (L, i);     Lua_pushnumber (L, sum/n);         Press average Lua_pushnumber (L, sum);                       Press in and return 2;      Returns two results} static int Sayhellofunc (lua_state* L) {printf ("Hello world!");  return 0; } static const struct Lual_reg mylib[] = {{"average", averagefunc}, {"SayHello", Sayhellofunc}, {NUL     L, NULL}//The last pair in the array must be {null, NULL}, to indicate the end};      int Luaopen_mlualib (lua_state *l) {lual_register (L, "SS", Mylib);       return 1; The Mylib table is pressed into the stack, so you need to return 1} 
don't understand it's okay, let's compile it and then create a new Lua file that we'll call in Lua: (Remember to copy the DLL file to the Lua file directory before calling)
Require "Mlualib"  local ave,sum = Ss.average (1,2,3,4,5)//parameter corresponds to data in the stack  print (ave,sum)  --3  Ss.sayhello ()   --Hello world!

Successful call to have wood there? We see the output information.

What's going on here? Comb:

1. We have written averagefunc averaging and sayhellofunc functions,

2. Then wrap the function inside the mylib array, the type must be Lual_reg

3. The two functions are exported by the Luaopen_mlualib function and registered in LUA.

So why write like this? In fact, when we're in Lua:

Require "Mlualib"
That 's what LUA does when it's written like this:
Local Path = "MLualib.dll"    local f = package.loadlib (path, "Luaopen_mlualib")   --Return luaopen_mlualib function  f ()                                                 --Execution

So when we write a module like this, when writing the luaopen_xxx export function, XXX is best to be the same as the project name (because the project name and DLL). It is important to note that the lua_state in the function arguments are private and each function has its own stack. The stack is automatically emptied when a C/C + + function presses the return value into the LUA stack.

Lua and C + + interaction detailed Summary _4_lua call C + +

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.