C/C++與lua二維數組交互的經典範例

最近爲了解決skynet的跑得快ai的核心算法性能問題,那麼我們自然就用C來寫核心算法,之前從來沒做過二維數組交互,也是折騰了一番才能正常理解與運行。先看示例代碼

//數組計算加一返回數組
int GetCardCal(lua_State* L)
{
	int arrayNum[20][20] = { 0 };
		lua_pushnil(L);
		int index = lua_gettop(L)-1;
		luaL_checktype(L, index, LUA_TTABLE); //檢測傳遞過來的是否爲table
		int indexA = 0;
		while (lua_next(L, index)) {
			int tempindex = lua_gettop(L);
			lua_pushnil(L);
			int count = 0;
			while (lua_next(L, tempindex)) {
				int card = luaL_checkinteger(L, -1);
				arrayNum[indexA][count++] = card;
				lua_pop(L, 1);				// pop value
			}
			indexA++;
			lua_pop(L, 1);				// pop value
		}
		for (int i = 0; i < 20;i++)
		{
			for (int j = 0; j < 20; j++)
			{
				if (arrayNum[i][j]>0)
				{
					arrayNum[i][j]++;
				}
			}
		}
		lua_newtable(L);
		lua_newtable(L);
		int arrayIndex1 = 1;
		for (int i = 0; i < 20; i++)
		{
			if (arrayNum[i][0]==0)
			{
				continue;
			}
			lua_newtable(L);

			int arrayIndex2 = 1;
			for (int j = 0; j < 20; j++)
			{
				if (arrayNum[i][j]>0)
				{
					lua_pushinteger(L, arrayNum[i][j]);
					lua_rawseti(L, -2, j + 1);
				}
				
			}
			lua_rawseti(L, -2, arrayIndex1++);
		}


	return 1;
}

測試用例

local vecResult={{56},{17},{53},{54},{72},{49,33},{72,56},{49,33,17,56,72},{49,33,17,53,54}}

 local allsortCardCal= CardAllSort.GetCardCal(vecResult)

做這個之前翻看了很多用例,嘗試了很多遍才能勉強理解得了幾個關鍵函數的操作,關鍵函數lua_next(L, index)

lua_next() 這個函數的工作過程是:
1) 先從棧頂彈出一個 key
2) 從棧指定位置的 table 裏取下一對 key-value,先將 key 入棧再將 value 入棧
3) 如果第 2 步成功則返回非 0 值,否則返回 0,並且不向棧中壓入任何值

有了這個解釋你就明白了lua_pushnil(L);爲什麼寫在了前面

lua_pushinteger(L, arrayNum[i][j]);
                    lua_rawseti(L, -2, j + 1);

兩句一起就是說要把剛放到棧頂的數據放到表裏面去,-2的位置是一個表來的。

運行的結果圖如何

例子雖然短小,但已經充分體現了lua與C的二維數組之間的交互,其實數組的交互還是用C++來交互好一點,因爲C++有vector,這樣就沒必要操心數組大小,越界問題發生,同時可適用範圍,擴展性要比C好很多。(C++的出現就是爲了解決C的這一通毛病)但老大要求與Skynet風格統一,沒辦法只能用C,沒寫之前千難萬難,學會了就容容易易。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章