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;

       }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章