一) 、建立lua源代码工程,编译lua的静态库

1、下载Lua源码 http://www.lua.org/download.html 

      a 下载后解压到一个目录下,这里假设解压到D:\lua-5.1.5b 注意下载的版本,如果是5.2.x,后面代码中的C API发生了改变

2、在VS2010中新建一个静态库项目,项目命名为lua

     a 选择新建 Win32 console project

     b 在wizard界面选择 static Library;不选择Precomplied Header

3、往工程中添加代码(Add -> Existing Item)

     a 添加D:\lua-5.1.5\src 目录下的*.h文件到项目的Header Files目录下

     b 添加D:\lua-5.1.5\src 目录下的*.c文件到项目的Source Files目录下

(可选)4、配置项目的属性,在项目的“配置属性” 界面中操作

    a Configuration Properties -> C/C++-> General -> Additional Include Directories 

       添加D:\lua-5.1.5\src

    b Configuration Properties -> C/C++-> Advanced -> compile as 

        这里的选择将影响后面代码中如何指定编译链接方式,后面的测试选择的是Compile as C code

(可选)5、 生产项目 Build

     如果是DEBUG mode 将在Debug目录下看到一个lua.lib文件,Release mode的lib文件在Release文件下


二)、后面添加一个项目尝试在C/C++代码中, 调用刚才的lua静态库

1、在解决方案中添加一个 Win32 console project,项目名称命名为testlua,后面wizard界面中的选项无需修改

2、添加对lua项目的引用

    a Common Properties -> Framework and References -> Add New References 

   选择lua项目

3、添加对头文件的include directory

   a Configuration Properties -> C/C++-> General -> Additional Include Directories 

  添加D:\lua-5.1.5\src

4、在项目的的在testlua.cpp文件中添加下面的代码




[cpp] ​​view plain​​ ​​copy​

 


  1. #include "stdafx.h"  
  2. #include <stdio.h>  
  3. #include <string.h>  
  4.   
  5. extern "C"  
  6. {  
  7. #include <lua.h>  
  8. #include <lualib.h>  
  9. #include <lauxlib.h>  
  10. }  
  11.   
  12. int _tmain(int argc, _TCHAR* argv[])  
  13. {  
  14.     lua_State *L = lua_open();  
  15.     luaL_openlibs(L);  
  16.   
  17.     const char *buf = "print('Hello World')";  
  18.     luaL_dostring(L,buf);  
  19.       
  20.     lua_close(L);  
  21.     getc(stdin);  
  22.     return 0;  
  23. }  


  


5,设置默认的项目,否则要去手动运行生成的可执行文件testlua.exe (见附图)

     Solution -> Properties -> Common Properties ->Startup Project ->Single startup project

     把默认的lua改为testlua

按F5或Ctrl+F5,将会在控制台中输入了Hello World。

 


附图1:在一个项目中添加另一个项目

VS2010编译、调用Lua程序_lua

附图2: 设置默认项目

VS2010编译、调用Lua程序_静态库_02

附图3:静态库

VS2010编译、调用Lua程序_静态库_03       或者       VS2010编译、调用Lua程序_c++_04