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