Lua 跟 C++ 的互動

來源:互聯網
上載者:User

標籤:data   cout   nts   檔案   csdn   表示   south   global   lis   

Lua 和 C++ 是這樣互動的

亂七八糟的前戲:
1. 到官網下載 Lua 檔案  可參考 ->   Lua 下載與配置
2. 設定環境  可參考  ->   VS 配置Lua環境


互動過程有:
1. C++ 訪問 Lua 的變數
2. C++ 調用 Lua 的函數
3. Lua 訪問 C++ 的變數
4. Lua 訪問 C++ 的函數


No code say a j8


C++ 調用 Lua

#include <iostream>#include <string>// 引入Lua必要的標頭檔,Version: Lua5.1.5extern "C"{#include "lua.h"#include "lualib.h"#include "lauxlib.h"};using namespace std;// C++ 調用 lua int main(){//初始化全域Llua_State *L = luaL_newstate();//開啟庫luaL_openlibs(L);//載入lua指令檔if (luaL_loadfile(L,"LuaFile\\lua.lua"))   // lua.lua 的路徑,這裡使用相對路徑{printf("file load error\n");}lua_pcall(L,0,0,0);    // 載入 Lua 檔案lua_getglobal(L, "l_str");  // get, 將L指向 lua檔案裡的函數 l_str lua_pcall(L,0,1,0);// 運行指標L指向的函數,將結果返回到棧頂, (0,1,0) 表示 (輸入個數,輸出個數,其它處理)string strVersion = luaL_checkstring(L,1);   // 從棧頂擷取元素cout<<strVersion<<endl;lua_close(L);return 0;}/*************************************Lua.luaversion = "Lua version: 5.1.5";function l_str()return version;end;print("Load LuaFile Accomplish");*************************************/


Lua 調用 C++

#include <iostream>#include <string>// 引入Lua必要的標頭檔,Version: Lua5.1.5extern "C"{#include "lua.h"#include "lualib.h"#include "lauxlib.h"};using namespace std;// 將lua中的變數,通過這個函數列印出來int c_Print(lua_State* L)// 傳回值為壓入棧中元素的個數{// 從參數列表中,擷取元素string strVersion = luaL_checkstring(L,1);cout<<strVersion<<endl;lua_pushstring(L, strVersion.c_str());// 將 strVersion 壓入棧。也能夠不壓return 1;    // 返回壓入棧中元素的個數}// Lua 調用 C++ 的函數int main(){//初始化全域Llua_State *L = luaL_newstate();//開啟庫luaL_openlibs(L);//載入lua指令檔if (luaL_loadfile(L,"LuaFile\\lua.lua"))   // lua.lua 的路徑,這裡使用相對路徑{printf("file load error\n");}lua_pcall(L,0,0,0);    // 載入 Lua 檔案lua_pushcfunction(L, c_Print);// 將C++函數push進來lua_setglobal(L, "c_Print");// 將C++函數進行注冊。這樣lua檔案就能識別到了。

lua_getglobal(L, "l_Print");lua_pcall(L,0,0,0);// 調用lua 中的 l_Print 函數lua_close(L);return 0;}/*************************************Lua.luaversion = "Lua version: 5.1.5";function l_Print()c_Print(version);end;print("Load LuaFile Accomplish");*************************************/


執行結果:



Lua 跟 C++ 的互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.