VC++6.0配置LUA环境和C++调用LUA的简单示例

一、VC++6.0配置LUA环境和C++调用LUA的简单示例

LUA版本: 5.1.3   http://www.lua.org下载lua 5.13源代码

编译lua 5.13源代码:(你可下载别人编译的,

配置LUA环境:工具→选项→目录,然后

include files:见图(修改为你的LUA相应路径即可)

library files:(同上)

可执行文件:D:/PROGRAM FILES/LUA-5.1.3/LUA-5.1.3/BIN(可略)

Test.lua的内容如下:

function MyLuaAdd ( x, y)

   return x + y

end

       VC++.cpp内容如下:(解释见“C/C++函数调用LUA函数”部分)

       //运行时,复制lua51.dll.cpp同路径下(或系统的system32,如:C:/WINDOWS/system32)

       // include部分是上图中绿框中的内容

       int main()

       {

              lua_State* L = lua_open();  // 初始化LUA环境

             

              luaopen_base(L);  //  打开LUA基本库

              //    luaopen_table(L);

              //    luaopen_string(L);

              //    luaopen_math(L);

              //    luaL_openlibs(L);

             

              int iError;

              iError = luaL_loadfile(L, "Test.lua");  // 装载LUA文件

              if (iError) {

                     std::cout  << "Load script FAILED! "

                                          << lua_tostring(L, -1)  // query error

                                          << std::endl;

                     lua_close(L);

                     return 1;

              }

             

              iError = lua_pcall(L, 0, 0, 0); // 测试是否支持lua_pcall

              if (iError) {

                     std::cout  << "pcall FAILED "

                                          << lua_tostring(L, -1)  // query error

                                          << iError

                                          << std::endl;

                     lua_close(L);

                     return 1;

              }

 

              lua_getglobal(L, "MyLuaAdd");   // push  MyLuaAdd-fuction

              lua_pushnumber(L, 10);          // push  first-argument

              lua_pushnumber(L, 11);          // push  second-argument

              lua_pcall(L, 2, 1, 0);          // call fuctionMyLuaAdd

              std::cout  << " MyLuaAdd (10, 11) == "

                                   << lua_tonumber(L, -1)      // query  result

                                   << std::endl;

              lua_pop(L,1);                   // discard result from stack

              lua_close(L);

              getch();

              return 0;

       }

 

你可能感兴趣的:(LUA)