C語(yǔ)言中通過(guò)LUA API訪問(wèn)LUA腳本變量的簡(jiǎn)單例子
1.簡(jiǎn)介
這一節(jié)介紹一些關(guān)于棧操作、數(shù)據(jù)類(lèi)型判斷的LUA API,可以使用這些函數(shù)獲得腳本中的變量值。
2.步驟
編寫(xiě) test01.lua 腳本,在VS2003中創(chuàng)建控制臺(tái)C++程序并正確配置,執(zhí)行查看結(jié)果,修改test02.lua腳本后查看執(zhí)行結(jié)果
3.測(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。
4.控制臺(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;
}
相關(guān)文章
Lua教程(二):基礎(chǔ)知識(shí)、類(lèi)型與值介紹
這篇文章主要介紹了Lua教程(二):基礎(chǔ)知識(shí)、類(lèi)型與值介紹,本文講解了Hello World程序、代碼規(guī)范、全局變量、類(lèi)型與值等內(nèi)容,需要的朋友可以參考下2015-04-04Lua教程(六):綁定一個(gè)簡(jiǎn)單的C++類(lèi)
這篇文章主要介紹了Lua教程(六):綁定一個(gè)簡(jiǎn)單的C++類(lèi),本文是最后一篇C/C++與Lua交互的教程,其他教程請(qǐng)參閱本文下方的相關(guān)文章,需要的朋友可以參考下2014-09-09Lua中的異常處理pcall、xpcall、debug使用實(shí)例
這篇文章主要介紹了Lua中的異常處理pcall、xpcall、debug使用實(shí)例,這3個(gè)函數(shù)是Lua中的異常處理必須用到的,需要的朋友可以參考下2014-09-09Lua中的閉合函數(shù)、非全局函數(shù)與函數(shù)的尾調(diào)用詳解
這篇文章主要介紹了Lua中的閉合函數(shù)、非全局函數(shù)與函數(shù)的尾調(diào)用詳解,本文對(duì)這2種函數(shù)和尾調(diào)用做了深入研究,需要的朋友可以參考下2014-09-09