(Lua) C++ 寫函式,Lua 呼叫使用
阿新 • • 發佈:2019-01-09
C++ 裡頭寫一個 Function 但是透過 Lua 提供input引數並且回傳結果給Lua 輸出的辦法。
Lua 檔案
1 local ave, sum = average(22, 20, 45) 2 print("ave : ", ave, "sum = ", sum)
C++ 檔案
1 int average(lua_State *L){ 2 3 int lua_args_count = lua_gettop(L); 4 5 lua_Number sum = 0; 6 for (int i = 0; i < lua_args_count; i++){7 sum += lua_tonumber(L, i); 8 } 9 10 lua_pushnumber(L, sum / lua_args_count); // follow order to return value ave 11 lua_pushnumber(L, sum); // sum 12 13 // return 2 number to Lua 14 return 2; 15 } 16 17 int main(int argc, const char *argv[]) 18 { 19 //cout << "lua test platform!!!" << endl;20 string scriptnema = "main.lua"; 21 string script_char = "print('123')"; 22 23 int luaError; 24 lua_State *L = luaL_newstate(); 25 if (L == NULL) 26 { 27 cout << "luaL_newstate faile !!!" << endl; 28 return -1; 29 } 30 luaL_openlibs(L);
31lua_register(L, "average", average); // "average" --> Lua symbol call C++ function method (local ave, sum = average(11, 20, 63)) 32 33 luaError = luaL_dofile(L, scriptnema.c_str()); 34 lua_close(L); 35 system("pause"); 36 return 0; 37 }
第31行,這邊主要是讓Lua symbol 可以辨識 average的感覺,還有另一種辦法可以自己創造一個
自己的Lua環境(Lib),打算在下一篇紀錄下來。
// "average" --> Lua symbol call C++ function method (local ave, sum = average(11, 20, 63)) lua_register(L, "average", average);