বিষয়বস্তুতে চলুন

মডিউল:TableTools

From ওয়ার্ল্ডপিডিয়া, the free encyclopedia
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