Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- vim: set noexpandtab tabstop=3 :miv --
- -- Note: To make reading of this codebase more enjoyable, please consider typing
- -- :%s/other/otter/
- -- into your vim command line.
- local function tokenize(tokens, values, reference, target)
- for key, value in pairs(reference) do
- if tokens[value] then
- if target[key] then
- rawset(values, tokens[value], target[key])
- else
- return nil
- end
- else
- if type(value) == 'table' and type(target[key]) == 'table' then
- if not tokenize(tokens, values, reference[key], target[key]) then
- return nil
- end
- else
- if target[key] ~= value then
- return nil
- end
- end
- end
- end
- -- Abort if target has extra values -- Really though?
- for key, value in pairs(target) do
- -- I don't like how this iterates over everything again
- -- Maybe there's another way of doing this, dunno
- if reference[key]==nil then -- Remember to accept `false` as a value
- return nil
- end
- end
- return values
- end
- local function match(reference)
- local tokens = {}
- local _tokens = {}
- -- Make "unused" globals resolve to tokens
- env = setmetatable({}, {__index=function(self, key)
- local super=_G[key] do
- if super then
- return super
- else
- if _tokens[key] then
- return _tokens[key]
- else
- local token = {}
- tokens[token] = key
- _tokens[key] = token
- return token
- end
- end
- end
- end})
- reference = reference(env)
- return function(target)
- local values = tokenize(tokens, {}, reference, target)
- if values then
- setmetatable(values, {__index=_G})
- return function(code)
- return code(values)
- end
- else
- return function()
- end
- end
- end
- end
- --[============================================================================[
- This is where the magic ends and the showcase begins ;)
- --]============================================================================]
- local pair = match(function(_ENV)
- return {
- { name = 'alice' },
- { name = other }
- }
- end)
- local maybe = pair {
- { name = 'alice' },
- { name = 'bob' }
- }
- maybe(function(_ENV)
- print(other)
- end)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement