Tuple 模組

lua-users home
wiki

微不足道的 n 元組實作方式。包含 NaN 的元組只會與自身相等(完全相同的 экземпляр)。將其儲存為「tuple.lua」。關於用法,請參閱 MultipleKeyIndexing

--[[

	(...) -> tuple
	wrap(t, [n]) -> tuple

]]

local setmetatable, select, table, tostring =
	  setmetatable, select, table, tostring

setfenv(1, {})

local meta = {__type = 'tuple'}

local function wrap(t, n)
	t.n = n or t.n or #t
	setmetatable(t, meta)
	return t
end

local function new(...)
	return wrap({n=select('#',...),...})
end

function meta:__eq(other)
	if self.n ~= other.n then
		return false
	end
	for i=1,self.n do
		if self[i] ~= other[i] then
			return false
		end
	end
	return true
end

function meta:__tostring()
	local t = {}
	for i=1,self.n do
		t[i] = tostring(self[i])
	end
	return '('..table.concat(t, ', ', 1, self.n)..')'
end

local M = {
	meta = meta,
	wrap = wrap,
	new = new,
}

return setmetatable(M, {__call = function(_,...) return new(...) end})

另請參閱

Renato Maia 的類似手法:http://www.tecgraf.puc-rio.br/~maia/lua/tuple/


RecentChanges · 偏好設定
編輯 · 歷史記錄
最後編輯日期為 2012 年 2 月 28 日下午 8:55 GMT (差異)