
正文
(Lua) C++ 呼叫 Lua 的變數、函式
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
簡單的在C++裡頭與Lua交互操作
首先提供 Lua 的簡單範例
print(" Lua 2019/01/07 !!!")
-- Variable
monster_type = "Ghost"
blood = 99.9
-- Table
x_table = {, , }
-- Function
function f(var)
return var * var + * var +
end
呼叫變數的辦法
int main(int argc, const char *argv[])
{
string scriptnema = "main.lua";
int luaError;
lua_State *L = luaL_newstate(); if (L == NULL)
{
cout << "luaL_newstate faile !!!" << endl;
return -;
} luaL_openlibs(L);
// first getbloable parameter that it will be first on the stack.
// stack index number will follow small to large [1 ... 5] or [-5 ... -1]
lua_getglobal(L, "blood");
lua_getglobal(L, "monster_type"); double blood = lua_tonumber(L, ); // index = 1 or -2
string type = lua_tostring(L, ); // index = -1 or 2 cout << "blood = " << blood << endl;
cout << "monster_typa = " << type.c_str() << endl; }
呼教 table的方式
int main(int argc, const char *argv[])
{
//cout << "lua test platform!!!" << endl;
string scriptnema = "main.lua";
int luaError;
lua_State *L = luaL_newstate(); if (L == NULL)
{
cout << "luaL_newstate faile !!!" << endl;
return -;
} luaL_openlibs(L);
luaL_dofile(L, scriptnema.c_str()); lua_getglobal(L, "x_table");
lua_Integer array_len = luaL_len(L, -);
cout << "array_len = " << array_len << endl; for (int i = ; i > ; i--){
lua_rawgeti(L, -, i); // lua_rawgeti(lua stack, index, value)
cout << lua_tonumber(L, -) << endl;
lua_pop(L, );
}
}
在 C++ 輸入變數給 Lua 且 return 結果
int luaf(lua_State *L){
double sum;
lua_getglobal(L, "f");
lua_pushnumber(L, );
lua_call(L, , ); // lua_call(lua stack, input num, output num)
sum = (int)lua_tonumber(L, );
lua_pop(L, );
return sum;
}
int main(int argc, const char *argv[])
{
//cout << "lua test platform!!!" << endl;
string scriptnema = "main.lua";
int luaError;
lua_State *L = luaL_newstate();
if (L == NULL)
{
cout << "luaL_newstate faile !!!" << endl;
return -;
}
luaL_openlibs(L);
luaL_dofile(L, scriptnema.c_str());
cout << luaf(L) << endl;
lua_close(L);
system("pause");
}
以上是 Lua --> Stack 基本API應用,希望最後是把所有的API都玩過一遍。
這樣之後學習與應用時可以更加靈活








