I recently learned Lua and made some notes.
To use LUA in C + +, it was the first time that a LUA parser was needed ... From (http://www.lua.org/) This site can be down to. I am here to download the lua5.3 source code, you can clone a copy of my vs2013 project (https://git.oschina.net/liLinux/lua-5.3.git) from this git library. has been set up, can be compiled into a static library or a dynamic library is OK.
Calling Lua in C is very basic and simple. So directly on the code
Calllua.lua content in Lua called by C
Width = 100; Height = 100;function f (x, Y) return (x^2 * Math.sin (Y))/(1-x); end
. c Files
#include "stdafx.h" #include <string.h> #include <lua.hpp> #include <stdlib.h> #ifndef _debug#ifndef _ Unicode#pragma comment (lib, "Static.lib") #else #pragma comment (lib, "Static_u.lib") #endif//!_unicode#else#ifndef _ Unicode#pragma comment (lib, "Static_d.lib") #else #pragma comment (lib, "Static_ud.lib") #endif//!_UNICODE#ENDIF//!_ Debug//===========double f (Double x, double y) {double Dreturn = 0.0;lua_state* L = Lual_newstate (); Luaopen_base (L); Loading LUA Base library lual_openlibs (L); Load LUA Generic extension library//load LUA file if (0! = Lual_loadfile (L, ". \\callLua.lua")) error (L, "load file failed:%s", lua_tostring (L,-1)); F (0! = Lua_pcall (l, 0, 0, 0)) error (L, "cannot run configuration file:%s", lua_tostring (L,-1));//Get global variables in Lua Lua_getgloba L (L, "width"), if (!lua_isnumber (L,-1)) error (L, "' width ' should be a number\n");p rintf ("width:%lf,", Lua_tonumber (L,-1) ), Lua_pop (l,1), Lua_getglobal (L, "height"), if (!lua_isnumber (l,-1)) error (L, "' height ' should be a number\n");p rintf (" Height%.lf\n ", lua_tonumber(L,-1)); Lua_pop (l,1);//Invoke functions in Lua/*push functions and Arguments*/lua_getglobal (L, "F"); The function is first into the stack lua_pushnumber (L, x); The parameters are entered in the Stack lua_pushnumber (l, y);/*do the call (2 arguments, 1 result*/if (0! = Lua_pcall (L, 2, 1, 0))//execute will automatically pop up the stack for functions and used parameters, and Press the return value into the stack error (L, "error runing function ' F ':%s", lua_tostring (L,-1)); /*retrieve result*/if (!lua_isnumber (L,-1)) error (L, "Functiogn ' F ' must return a number");d return = Lua_tonumber (l ,-1); Lua_pop (L, 1); Lua_close (l); return Dreturn;} void Test () {printf ("Value:%lf\n", F (10, 12));} int _tmain (int argc, _tchar* argv[]) {Test (); System ("pause"); return 0;}
Lua is called in C + +