前言#
前面幾篇都是講c/c++代碼對lua文件中數(shù)據(jù)的讀取和設(shè)置,這一篇我們來看看對數(shù)據(jù)類型的判斷,這是非常有用的,便于我們針對于不同的類型進行不同的操作,比如打印工作,對于數(shù)值類型的數(shù)據(jù)我們可以使用%d打印,而對于字符串類型的數(shù)據(jù)我們可以使用%s打印,這些判斷的前提就是得知道數(shù)據(jù)是什么類型的。
內(nèi)容#
lua_type##
- 原型:int lua_type (lua_State *L, int index);
- 解釋:返回給定索引處的值的類型,當索引無效時則返回LUA_TNONE(那是指一個指向堆棧上的空位置的索引)。lua_type 返回的類型是一些個在lua.h中定義的常量:LUA_TNIL,LUA_TNUMBER,LUA_TBOOLEAN
,LUA_TSTRING,LUA_TTABLE,LUA_TFUNCTION,LUA_TUSERDATA,LUA_TTHREAD,LUA_TLIGHTUSERDATA。
lua_typename##
- 原型:const char *lua_typename (lua_State *L, int tp);
- 解釋:返回tp表示的類型名,這個tp必須是 lua_type 可能返回的值中之一。
Usage##
- 首先我們來新建一個文件,命名文件為typetest.lua編寫代碼如下:
-- 定義一個全局table
information =
{
name = "AlbertS",
age = 22,
married = false,
}
-- 定義一個打印函數(shù)
function func_printtable()
print("\nlua --> table elemet:");
for index,value in pairs(information) do
print("information."..index.." = ".. tostring(value));
end
end
- 然后編寫c++調(diào)用代碼如下:
lua_State *L = lua_open();
luaL_openlibs(L);
luaL_dofile(L,"typetest.lua"); // 加載執(zhí)行l(wèi)ua文件
lua_getglobal(L,"information"); // 將全局表壓入棧
lua_pushstring(L, "name"); // 將要取的變量名壓入棧
lua_gettable(L, -2); // 取information.name的值
int luatype = lua_type(L, -1); // 取information.name的類型 -->lua_type用法
if(LUA_TNONE == luatype)
{
printf("\nc++ --> information.name type error\n");
}
else
{
printf("\nc++ --> information.name type is %s\n",
lua_typename(L, luatype)); // -->lua_typename用法
}
lua_pop(L,1);
lua_pushstring(L, "age"); // 將要取的變量名壓入棧
lua_gettable(L, -2); // 取information.age的值
luatype = lua_type(L, -1); // 取information.age的類型-->lua_type用法
if(LUA_TNONE == luatype)
{
printf("\nc++ --> information.age type error\n");
}
else
{
printf("\nc++ --> information.age type is %s\n",
lua_typename(L, luatype)); // -->lua_typename用法
}
lua_pop(L,1);
lua_pushstring(L, "married"); // 將要取的變量名壓入棧
lua_gettable(L, -2); // 取information.married的值
luatype = lua_type(L, -1); // 取information.married的類型-->lua_type用法
if(LUA_TNONE == luatype)
{
printf("\nc++ --> information.married type error\n");
}
else
{
// -->lua_typename用法
printf("\nc++ --> information.married type is %s\n",
lua_typename(L, luatype));
}
lua_pop(L,1);
lua_getglobal(L, "func_printtable");// 查看一下table的內(nèi)容
lua_pcall(L, 0, 0, 0);
lua_close(L); //關(guān)閉lua環(huán)境
- 結(jié)果

type.png
結(jié)論#
- 在對數(shù)據(jù)類型不明確的情況下可以使用lua_type和lua_typename兩api組合起來,用來判斷數(shù)據(jù)的類型。
- 取到數(shù)據(jù)的類型后需要判斷類型是否為LUA_TNONE癩皮面后面調(diào)用出現(xiàn)問題。
- 通過最后的遍歷table我們可以發(fā)現(xiàn)使用pairs遍歷的table和我們初始化table元素的順序并不相同。