C++中通過(guò)LUA API訪問(wèn)LUA腳本變量學(xué)習(xí)教程
C++中通過(guò)LUA API訪問(wèn)LUA腳本變量學(xué)習(xí)是本文要介紹的內(nèi)容,主要是來(lái)學(xué)習(xí)一些關(guān)于棧操作、數(shù)據(jù)類型判斷的LUA API,可以使用這些函數(shù)獲得腳本中的變量值。
1、步驟
編寫(xiě) test01.lua 腳本,在VS2003中創(chuàng)建控制臺(tái)C++程序并正確配置,執(zhí)行查看結(jié)果,修改test02.lua腳本后查看執(zhí)行結(jié)果
2、測(cè)試腳本
以下是用來(lái)測(cè)試的lua腳本
- function plustwo(x)
- local a = 2;
- return x+a;
- end;
- rows = 6;
- cols = plustwo(rows);
上面的腳本定義了一個(gè)函數(shù)、兩個(gè)全局變量(LUA腳本變量默認(rèn)是全局的)。之后的C++程序中,我們將通過(guò)棧操作獲得這兩個(gè)變量 rows, cols
3、控制臺(tái)程序
- #include <iostream>
- extern "C"
- {
- #include "lua.h"
- #include "lauxlib.h"
- #include "lualib.h"
- }
- using namespace std;
- int main(int argc, char* argv[])
- {
- cout << "01_Read_Stack" << endl;
- /**//* Create a LUA VMachine */
- lua_State *L = lua_open();
- luaopen_base(L);
- luaopen_table(L);
- luaL_openlibs(L);
- luaopen_string(L);
- luaopen_math(L);
- int iError;
- iError = luaL_loadfile(L, "../test01.lua");
- if (iError)
- {
- cout << "Load script FAILED!" << lua_tostring(L, -1)<< endl;
- lua_close(L);
- return 1;
- }
- iError = lua_pcall(L, 0, 0, 0);
- if (iError)
- {
- cout << "pcall FAILED"<< lua_tostring(L, -1)<< iError<< endl;
- lua_close(L);
- return 1;
- }
- lua_getglobal(L, "rows");
- lua_getglobal(L, "cols");
- if (!lua_isnumber(L, -2))
- {
- cout << "[rows] is not a number" << endl;
- lua_close(L);
- return 1;
- }
- if (!lua_isnumber(L, -1))
- {
- cout << "[cols] is not a number" << endl;
- lua_close(L);
- return 1;
- }
- cout << "[rows]"
- << static_cast<int> (lua_tonumber(L, -2))
- << "[cols]"
- << static_cast<int> (lua_tonumber(L, -1))
- << endl;
- lua_pop(L,2);
- lua_close(L);
- return 0;
- }
小結(jié):C++中通過(guò)LUA API訪問(wèn)LUA腳本變量學(xué)習(xí)教程的內(nèi)容介紹完了,希望通過(guò)本文的學(xué)習(xí)能對(duì)你有所幫助!