مندرجات کا رخ کریں

ماڈیول:TableTools

From ورلڈپیڈیا, the free encyclopedia
نظرثانی بتاریخ 16:40، 15 دسمبر 2013ء از enwiki>Mr. Stradivarius (start module with useful tools for dealing with Lua tables)
(فرق) → پرانا نسخہ | تازہ ترین نسخہ (فرق) | تازہ نسخہ ← (فرق)

"اس ماڈیول کی دستاویز ماڈیول:TableTools/دستاویز پر بنائی جاسکتی ہے"

-- This module includes a number of functions that can be useful when dealing with Lua tables.

local p = {}

-- Define often-used variables and functions.
local floor = math.floor
local infinity = math.huge

--[[
-----------------------------------------------------------------------------------
-- Helper functions
-----------------------------------------------------------------------------------
--]]

local function isPositiveInteger(num)
	-- Returns true if the given number is a positive integer, and false if not.
	if type(num) == 'number' and num >= 1 and floor(num) == num and num < infinity then
		return true
	else
		return false
	end
end

--[[
-----------------------------------------------------------------------------------
-- compressSparseArray
--
-- This takes an array with one or more nil values, and removes the nil values
-- while preserving the order, so that the array can be safely traversed with
-- ipairs.
-----------------------------------------------------------------------------------
--]]
function p.compressSparseArray(t)
	local nums, ret = {}, {}
	for k, v in pairs(t) do
		if isPositiveInteger(k) then
			nums[#nums + 1] = k
		end
	end
	table.sort(nums)
	for _, num in ipairs(nums) do
		ret[#ret + 1] = t[num]
	end
	return ret
end

return p