intaverage(lua_State *L) { // get number of arguments int n = lua_gettop(L); double sum = 0; int i; // 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里面调用此函数
1 2 3
avg, sum = average(10, 20, 30, 40, 50) print("The average is ", avg) print("The sum is ", sum)
intdisplayLuaFunction(lua_State *l) { // number of input arguments int argc = lua_gettop(l); // print input arguments std::cout << "[C++] Function called from Lua with " << argc << " input arguments" << std::endl; for(int i=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 values std::cout << "[C++] Returning some values" << std::endl; lua_pushnumber(l, 12); lua_pushstring(l, "See you space cowboy"); // number of return values return2; }
注册此Lua函数
1 2 3 4
// push the C++ function to be called from Lua std::cout << "[C++] Pushing the C++ function" << std::endl; lua_pushcfunction(L, displayLuaFunction); lua_setglobal(L, "displayLuaFunction");
注意,上一个示例,我们使用的是函数是
1
lua_register(L, "average", average);
它其实只是一个宏定义,其实现也是上面两个函数组成的。
在Lua里调用此函数
1 2 3 4
io.write('[Lua] Calling the C functionn') a,b = displayLuaFunction(12, 3.141592, 'hola') -- print the return values io.write('[Lua] The C function returned <' .. a .. '> and <' .. b .. '>\n')