標籤:
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資料