A trick. C + + Call LUA code profile function (with code)

Source: Internet
Author: User
Tags error handling lua
There are two functions in the Lua file, then call the code with the CPP file, finally, there is a critical step, compile, we need to add additional options: g++ main.cpp-o main-llua-ldl. The process looks simple and requires hands-on operation.

First you install the Lua dev, which is simple to install:

Yum Install Lua-devel

Well, many Linux systems have lua but no dev and a little pit.

Here is the Lua file, which has two functions:

function Add (A, B)    return a + b endfunction hello ()    print ("Hello Lua!!!") End

After that is the call code for the CPP file:

 #include <iostream> #include <string>using std::cout;using std:: Endl;using Std::string;//extern, use the following file as a C-style file using extern "C" {#include <lua.h> #include <lauxlib.h> #inc    Lude<lualib.h>}int Main () {//create environment Lua_state *l = Lual_newstate ();        if (L = = NULL) {cout << "state error" << Endl;     return-1;    }//Load library lual_openlibs (L);    Const string file = "Func.lua";    Load file int ret = Lual_dofile (L, File.c_str ());        if (ret) {cout << "Dofile error" << Endl;     return-1;    } The//hello function does not have parameters, call Lua_getglobal (L, "hello") directly; Lua_pcall (L, 0, 0, 0);      Three 0 meanings, 0 arguments, 0 return value, 0 custom error handling Lua_getglobal (L, "add");      Two parameters are passed to the Add function, 1 and 2 are passed directly, and the variable is OK lua_pushnumber (L, 1);     Lua_pushnumber (L, 2);            Lua_pcall (l,2,1,0);    The return value is placed in the position of-1 cout << lua_tonumber (L,-1) << Endl;    Lua_close (L); return 0;} 

Finally, there is a critical step, and we need to add additional options when compiling:

g++ main.cpp-o MAIN-LLUA-LDL

Look at the results:

Done

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.