Created
August 26, 2019 07:48
-
-
Save cuixin/16a422606dd09ac6999032dfa2d1e014 to your computer and use it in GitHub Desktop.
lua match pattern example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local Receiver = {} do | |
Receiver.__index = Receiver | |
function Receiver.new(t) | |
return setmetatable(t or {}, Receiver) | |
end | |
function Receiver:__newindex(k, v) | |
assert(type(v) == "function") | |
local curr = self | |
for comp in k:gmatch "(%w+)" do | |
local v = curr[comp] | |
if not v then v = {}; rawset(curr, comp, v) end | |
curr = v | |
end | |
curr.__call = v | |
end | |
function Receiver:__call(msg) | |
local parent, key = self, nil | |
for i, key in ipairs(msg) do | |
key = tostring(key) | |
local v = parent[key] | |
if not v then return end | |
if v.__call then v.__call(table.unpack(msg, i)) end | |
parent = v | |
end | |
end | |
end | |
local receiver = Receiver.new() | |
function receiver:lua(...) | |
print("lua", ...) | |
end | |
function receiver:lua_tcp(...) | |
print("lua_tcp", ...) | |
end | |
function receiver:after_50000(...) | |
print("after", ...) | |
end | |
receiver { "lua", "tcp", 1000 } | |
receiver { "after", 50000, "foo" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment