intaverage(lua_State*L){// get number of arguments intn=lua_gettop(L);doublesum=0;inti;// loop through each argument for(i=1;i<=n;i++){// total the arguments sum+=lua_tonumber(L,i);}// push the average lua_pushnumber(L,sum/n);// push the sum lua_pushnumber(L,sum);// return the number of results return2;}
注册此函数给Lua
1
lua_register(L,"average",average);
Lua里面调用此函数
123
avg,sum=average(10,20,30,40,50)print("The average is ",avg)print("The sum is ",sum)
示例二
定义C++函数
1234567891011121314151617181920
intdisplayLuaFunction(lua_State*l){// number of input argumentsintargc=lua_gettop(l);// print input argumentsstd::cout<<"[C++] Function called from Lua with "<<argc<<" input arguments"<<std::endl;for(inti=0;i<argc;i++){std::cout<<" input argument #"<<argc-i<<": "<<lua_tostring(l,lua_gettop(l))<<std::endl;lua_pop(l,1);}// push to the stack the multiple return valuesstd::cout<<"[C++] Returning some values"<<std::endl;lua_pushnumber(l,12);lua_pushstring(l,"See you space cowboy");// number of return valuesreturn2;}
注册此Lua函数
1234
// push the C++ function to be called from Luastd::cout<<"[C++] Pushing the C++ function"<<std::endl;lua_pushcfunction(L,displayLuaFunction);lua_setglobal(L,"displayLuaFunction");