深入lua棧互動—cpp調用lua資料

來源:互聯網
上載者:User

標籤:


lua是通過lua_state這個棧來和c 互動的

1.....lua棧 index 下往上增長 如: 1 2 3 4 5 62.....lua棧 index 是迴圈的 如下 index 上到下 是 3 2 1 0 -1 -2 -3 ,棧對應的值為    1    2    3    x    1    2    3    3......lua函數多個傳回值如果上面是function返回了3個傳回值,那麼return a ,b,c  中 a=3 b=2 c=1 第一個傳回值先入棧

棧pop問題:lua_pop(x) ;x 為 pop的個數 ,一般調用函數後 pop(1) 因為一般傳回值只有一個

ps:調用函數的時候 不會堆棧平衡,返回時已經平衡了,值需要對返回的值  佔用的棧清理




c++使用lua的資料 例子

extern "C"{#include "src/lualib.h"#include "src/lauxlib.h"#include "src/lua.h"}#include "iostream"using namespace std;lua_State*l;int get_sum(int x, int y){int sum=0;lua_getglobal(l, "get_sum");/*調用函數*/lua_pushnumber(l, x);lua_pushnumber(l, y); lua_call(l, 2, 3);/*參數2個,傳回值3個*/cout << "top is  " << lua_gettop(l) << endl;cout << lua_tonumber(l, lua_gettop(l) - 0) << endl;cout << lua_tonumber(l, lua_gettop(l) - 1) << endl;cout << lua_tonumber(l, lua_gettop(l) - 2) << endl;cout << lua_tonumber(l, lua_gettop(l) - 2) << endl;cout << lua_tonumber(l, lua_gettop(l) - 3) << endl;cout << lua_tonumber(l, lua_gettop(l) - 4) << endl;cout << lua_tonumber(l, lua_gettop(l) - 5) << endl;cout << lua_tonumber(l, lua_gettop(l) - 6) << endl;cout << lua_tonumber(l, lua_gettop(l) - 7) << endl;cout << lua_tonumber(l, lua_gettop(l) - 8) << endl;cout << lua_tonumber(l, lua_gettop(l) - 9) << endl;lua_pop(l, 3);/*function返回了3個值*/cout << "\n\n" << endl;lua_getglobal(l, "b");/*擷取變數 壓入棧中*/cout <<"b=" <<lua_tonumber(l, lua_gettop(l)/*1*/ ) << endl;lua_getglobal(l, "a");/*擷取變數 壓入棧中*/cout << "a=" << lua_tonumber(l, lua_gettop(l)/*1*/) << endl;lua_getglobal(l, "c");/*擷取變數 壓入棧中*/cout << "c=" << lua_tonumber(l, lua_gettop(l)/*1*/) << endl;lua_pop(l, 3);/*清除棧*/cout << "top is" << lua_gettop(l) << endl;return sum;}int main(){l = lua_open();luaL_openlibs(l);luaL_dofile(l, "a.lua");//cout << get_sum(1, 2) << endl;get_sum(1, 2);lua_close(l);system("pause");return 0;}



a=10;

b=11;

c=12;


function get_sum(arg_1,arg_2)

return arg_1+arg_2,"100","200";

end


深入lua棧互動—cpp調用lua資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.