1. 程式人生 > >(Lua) C++ 呼叫 Lua 的變數、函式

(Lua) C++ 呼叫 Lua 的變數、函式

簡單的在C++裡頭與Lua互動操作

首先提供 Lua 的簡單範例

 1 print(" Lua 2019/01/07 !!!")
 2 
 3 -- Variable
 4 monster_type = "Ghost"
 5 blood = 99.9
 6 
 7 -- Table
 8 x_table = {10, 20, 30}
 9 
10 -- Function
11 function f(var)
12     return var * var + 2 * var + 100
13 end

呼叫變數的辦法

 1 int main(int argc, const char *argv[])
2 { 3 string scriptnema = "main.lua"; 4 int luaError; 5 lua_State *L = luaL_newstate(); 6 7 if (L == NULL) 8 { 9 cout << "luaL_newstate faile !!!" << endl; 10 return -1; 11 } 12 13 luaL_openlibs(L); 14 // first getbloable parameter that it will be first on the stack.
15 // stack index number will follow small to large [1 ... 5] or [-5 ... -1] 16 lua_getglobal(L, "blood"); 17 lua_getglobal(L, "monster_type"); 18 19 double blood = lua_tonumber(L, 1); // index = 1 or -2 20 string type = lua_tostring(L, 2); // index = -1 or 2 21 22 cout << "
blood = " << blood << endl; 23 cout << "monster_typa = " << type.c_str() << endl; 24 25 }

呼教 table的方式

 1 int main(int argc, const char *argv[])
 2 {
 3     //cout << "lua test platform!!!" << endl;
 4     string scriptnema = "main.lua";
 5     int luaError;
 6     lua_State *L = luaL_newstate();
 7 
 8     if (L == NULL)
 9     {
10         cout << "luaL_newstate faile !!!" << endl;
11         return -1;
12     }
13 
14     luaL_openlibs(L);
15     luaL_dofile(L, scriptnema.c_str());
16 
17     lua_getglobal(L, "x_table");
18     lua_Integer array_len = luaL_len(L, -1);
19     cout << "array_len = " << array_len << endl;
20 
21     for (int i = 3; i > 0; i--){
22         lua_rawgeti(L, -1, i); // lua_rawgeti(lua stack, index, value)
23         cout << lua_tonumber(L, -1) << endl;
24         lua_pop(L, 1);
25     }
26 }

在 C++ 輸入變數給 Lua 且 return 結果

 1 int luaf(lua_State *L){
 2     double sum;
 3     lua_getglobal(L, "f");
 4 
 5     lua_pushnumber(L, 20);
 6 
 7     lua_call(L, 1, 1); // lua_call(lua stack, input num, output num)
 8 
 9     sum = (int)lua_tonumber(L, 1);
10 
11     lua_pop(L, 1);
12 
13     return sum;
14 }
15 
16 int main(int argc, const char *argv[])
17 {
18     //cout << "lua test platform!!!" << endl;
19     string scriptnema = "main.lua";
20     int luaError;
21     lua_State *L = luaL_newstate();
22 
23     if (L == NULL)
24     {
25         cout << "luaL_newstate faile !!!" << endl;
26         return -1;
27     }
28 
29     luaL_openlibs(L);
30     luaL_dofile(L, scriptnema.c_str());
31 
32     cout << luaf(L) << endl;
33     lua_close(L);
34     system("pause");
35 }

以上是 Lua --> Stack 基本API應用,希望最後是把所有的API都玩過一遍。

這樣之後學習與應用時可以更加靈活