First, compile the LUA official lib (see "compiling LUA" article)
Second, new C + + Empty Project
Third, add a reference to Lua's header file and Lib
1. Organize the header files provided by the official Lua to add references to these header files
Iv. Adding a reference to Lib
3, write the source code, LUA code. and place the Lua file in the source code peer directory
Test.cpp file:
#include <stdio.h>
You must provide a header file to use Lib. There are two ways in which Lib contains source code:
One is the direct inclusion of the source code itself, which is known as the static link library of the passive link libraries.
One is to indicate the location of the DLL that contains the source code. This kind of Lib is called dynamic link library.
This article uses a static link library
extern "C" {
#include "Lua.h"
#include "Lualib.h"
#include "Luaxlib.h"
};
A pointer to the LUA interpreter, which is executed by the LUA interpreter.
Lua_state *l;
int luaadd (int x, int y)
{
int sum;
Find a global function named add in the interpreter's code file
Lua_getglobal (L, "add");
Enter parameters for a function
Lua_pushnumber (L, x);
Lua_pushnumber (L, y);
Call the LUA function and indicate that the function has two input functions, two output functions
Lua_call (L, 2, 1);
Gets the stack top value of the interpreter value stack
sum = (int) lua_tonumber (L,-1);
Eject the top of the stack
Lua_pop (L, 1);
return sum;
}
int main (int argc, char *argv[])
{
int sum = 0;
Initializing the LUA interpreter
L = Lual_newstate ();
Luaopen_base (L);
Loading the LUA base library into the interpreter
Lual_openlibs (L);
Loading LUA scripts into the interpreter
Lual_loadfile (L, "Add.lua");
Parameter settings for the interpreter
Lua_pcall (L, 0, Lua_multret, 0);
Calling LUA functions
sum = Luaadd (10, 15);
printf ("The sum is%d\n", sum);
Turn off the LUA interpreter
Lua_close (L);
return 0;
}
V. Results of Operation:
C + + calls Lua