This refers to the call in linux. C and C ++ call Lua is slightly different, reflected in:
1. methods included in the header file
Direct include in C
1 #include <lua.h>2 #include <lualib.h>3 #include <lauxlib.h>
Add extern "c" to C ++"
1 extern "C"2 {3 #include <lua.h>4 #include <lualib.h>5 #include <lauxlib.h>6 }
2. Different compilation options
Gcc-o xxx. c-llua-ldl-Lm
G ++-o xxx. cpp-llua-ldl
The following is a simple example of calling Lua code using C ++.
Lua code (File Name: luafun. lua)
1 function add(x)2 print('luafun,x=',x)3 end
C ++ code. The comments section describes some alternative calls.
1 # include <iostream> 2 using namespace std; 3 4 extern "C" 5 {6 # include "lua. h "7 # include" lauxlib. h "8 # include" lualib. h "9} 10 11 # define my_lua_dofile (L, filename) (luaL_loadfile (L), (filename) | lua_pcall (L), 0, LUA_MULTRET, 0 )) 12 13 lua_State * GlobalL; 14 15 int main () 16 {17 GlobalL = luaL_newstate (); 18 int x = 10; 19 20 lua_gc (GlobalL, LUA_GCSTOP, 0 ); 21 luaL_openlibs (GlobalL); 22 lua_gc (GlobalL, LUA_GCRESTART, 0); 23 24 // luaL_dofile (GlobalL, "luafun. lua "); // execute lua file 25 26 int loaderr = luaL_loadfile (GlobalL," luafun. lua "); 27 cout <" loaderr = "<loaderr <endl; 28 lua_pcall (GlobalL, 0, LUA_MULTRET, 0); 29 // my_lua_dofile (GlobalL, "luafun. lua "); // replace the above three rows with 30 31 lua_getfield (GlobalL, LUA_GLOBALSINDEX," add "); 32 // lua_getglobal (GlobalL," add "); // replace the previous row 33 34 lua_pushnumber (GlobalL, x); // parameter 35 int callerr = lua_pcall (GlobalL, 1, 0, 0 ); 36 cout <"callerr =" <callerr <endl; 37 cout <lua_tostring (GlobalL,-1) <endl; 38 39 lua_close (GlobalL); 40}
In fact, it is too cumbersome to use this method directly. Because we need to write the parameter list and other content separately for each lua function, many people have encapsulated this. For details, see http://blog.csdn.net/nightfallrove/article/details/5729. In addition, pay attention to the compilation options during g ++ compilation.