----------------------------------------------------------------
-- 文件名: stub.lua
-- 日期: 2013-12-02
-- 描述: 简单的版本控制基本库
-- 作者: 盒子哥
-- 感谢: ace
----------------------------------------------------------------

LibStub = {libs = {}, minors = {} }

local string = string
local type = type
local assert = assert
-- LibStub:NewLibrary(major, minor)
-- major (string) - the major version of the library
-- minor (string or number ) - the minor version of the library
-- 
-- returns nil if a newer or same version of the lib is already present
-- returns empty library object or old library object if upgrade is needed
function LibStub:NewLibrary(major, minor)
	assert(type(major) == "string", "Bad argument #2 to `NewLibrary' (string expected)")
	minor = assert(tonumber(string.match(minor, "%d+")), "Minor version must either be a number or contain a number.")
	
	local oldminor = self.minors[major]
	if oldminor and oldminor >= minor then return nil end
	self.minors[major], self.libs[major] = minor, self.libs[major] or {}
	return self.libs[major], oldminor
end

-- LibStub:GetLibrary(major, [silent])
-- major (string) - the major version of the library
-- silent (boolean) - if true, library is optional, silently return nil if its not found
--
-- throws an error if the library can not be found (except silent is set)
-- returns the library object if found
function LibStub:GetLibrary(major, silent)
	if not self.libs[major] and not silent then
		error(("Cannot find a library instance of %q."):format(tostring(major)), 2)
	end
	return self.libs[major], self.minors[major]
end

-- LibStub:IterateLibraries()
-- 
-- Returns an iterator for the currently registered libraries
function LibStub:IterateLibraries() 
	return pairs(self.libs) 
end

setmetatable(LibStub, { __call = LibStub.GetLibrary })