C + + calls Lua

Source: Internet
Author: User

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

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.