C++調用Lua函數

int main()
{
lua_State * L = luaL_newstate();
luaL_openlibs(L);
luaL_dofile(L, "2.lua");

lua_getglobal(L,"test1");//調用無參無返回值函數
lua_pcall(L,0,0,-1);//有0個參數0個返回值,調用失敗返回-1

lua_getglobal(L,"test2");//調用有參無返回值函數
lua_pushnumber(L,1);
lua_pushnumber(L,2);
lua_pcall(L,2,0,-1);//有兩個參數0個返回值,調用失敗返回-1

lua_getglobal(L,"test3");//調用有參又返回至函數
lua_pushnumber(L,1);
lua_pushnumber(L,2);
lua_pcall(L,2,1,-1);//有兩個參數一個返回值,調用失敗返回-1
int num = lua_tonumber(L,-1);
printf("%d\n",num);

getchar();
return 0;

}



/**********************************2.lua************************************/



function test1()
print("調用成功");
end;


function test2(a,b)
print(a+b);
end;


function test3(a,b)
return a+b;
end;



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