Module:Sandbox/Artoria2e5/Fallback

This is an old revision of this page, as edited by Artoria2e5 (talk | contribs) at 14:20, 13 October 2016 (A mostly irrelevant util function...). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

-- A simple index fallback implementation for tables.
-- Useful for template argument aliasing.
-- Hmm, what about __newindex?

local function makeFallback(args, arg_aliases)
	local oldArgsMeta = getmetatable(args) or {}
	local newArgsMeta = {}
	
	-- Start the new metatable as a copy of the old metatable.
	for k, v in ipairs(oldArgsMeta) do
        newArgsMeta[k] = v
    end

    -- Change the __index metamethod to our implementation.
    -- See https://www.lua.org/pil/13.4.1.html.
    newArgsMeta.__index = function (t, k)
    	-- Try the old metamethod first.
    	-- Thanks to closures, this whole oldArgsMeta object will stay.
    	if oldArgsMeta.__index ~= nil then
    	    local val = oldArgsMeta.__index(t, k)
    	    if val ~= nil then
	    		return val
	        end
        end
		
		-- Now try use the aliases given.
		for _, v in ipairs(arg_aliases[k] or {}) do
			-- If a working value is found, use it.
		    if t[v] ~= nil and t[v] ~= '' then
		    	return t[v]
	    	end
		end
		return nil
	end
	setmetatable(args, newArgsMeta)
	return args  -- just in case someone wants a return value.
end

return makeFallback