Info Istruzioni per l'uso
Questo è un modulo scritto in Lua. Le istruzioni che seguono sono contenute nella sottopagina Modulo:Enum/man (modifica · cronologia)
Sandbox: Modulo:Enum/sandbox (modifica · cronologia) · Sottopagine: lista · Test: Modulo:Enum/test (modifica · cronologia · esegui)

Questo modulo implementa la classe Enum con cui si possono creare enumerazioni. È un metamodulo pensato per essere usato da altri moduli.

Esempio d'uso

Si importa il modulo:

local Enum = require('Modulo:Enum')

Si crea un enum:

local Option = Enum:new('nome identificativo', {
	OPTION_1 = {
		value = 'opzione 1'
	},
	OPTION_2 = {
		value = 'opzione 2'
	}
})

-- metodo per trovare la costante in base al valore
function Option:findByValue(value)
	return self:findBy('value', value)
end

A questo punto si usa l'enum tenendo a mente che:

-- supera il test
assert(Option.OPTION_1 == Option:findByValue('opzione 1'))

-- supera il test
assert(Option == Enum['nome identificativo'])

Si può anche decidere di esporre l'elenco delle costanti:

local p = {}

-- entrypoint per ottenere le costanti di un qualsiasi enum
function p.list_constants(frame)
	local enum_id = frame.args[1]
	local constants = {}

	for _, constant in pairs(Enum[enum_id]) do
		table.insert(constants, constant.value)
	end

	return table.concat(constants, ', ')
end

return p



--[[
* Modulo che implementa la classe Enum.
* È un metamodulo pensato per essere usato da altri moduli.
]]

require('strict')

local Enum = {}

function Enum:new(name, values)
	local e, mt = {}, {}

	assert(self[name] == nil)

	for key, value in pairs(values) do
		assert(type(value) == 'table')
		e[key], values[key] = value, nil
	end

	self[name] = e
	mt.__index = mt
	mt.__newindex = mt
	setmetatable(e, mt)
	setmetatable(mt, self)

	return e
end

function Enum.__index(mt, key)
	if type(getmetatable(mt)[key]) == 'function' and key ~= 'new' then
		return getmetatable(mt)[key]
	end
end

function Enum.__newindex(mt, key, value)
	if type(value) == 'function' then
		rawset(mt, key, value)
	end
end

function Enum:findBy(attribute, value)
	for _, constant in pairs(self) do
		if constant[attribute] == value then
			return constant
		end
	end
end

return Enum