lexical replacements

This commit is contained in:
David Muñoz 2014-12-26 12:13:27 +01:00
parent 8ca367e83b
commit d40346b481
2 changed files with 57 additions and 4 deletions

View File

@ -42,6 +42,25 @@ function msg_valid(msg)
end end
end end
function do_lex(msg, text)
local mutated = true
while mutated do
mutated = false
for name, desc in pairs(plugins) do
if (desc.lex ~= nil) then
result = desc.lex(msg, text)
if (result ~= nil) then
-- print ("Mutating to " .. result)
text = result
mutated = true
end
end
end
end
-- print("Text mutated to " .. text)
return text
end
-- Where magic happens -- Where magic happens
function do_action(msg) function do_action(msg)
local receiver = get_receiver(msg) local receiver = get_receiver(msg)
@ -52,18 +71,25 @@ function do_action(msg)
text = '['..msg.media.type..']' text = '['..msg.media.type..']'
end end
-- print("Received msg", text) -- print("Received msg", text)
text = do_lex(msg, text)
for name, desc in pairs(plugins) do for name, desc in pairs(plugins) do
-- print("Trying module", name) -- print("Trying module", name)
for k, pattern in pairs(desc.patterns) do for k, pattern in pairs(desc.patterns) do
-- print("Trying", text, "against", pattern) -- print("Trying", text, "against", pattern)
matches = { string.match(text, pattern) } matches = { string.match(text, pattern) }
if matches[1] then if matches[1] then
print(" matches",pattern) -- print(" matches",pattern)
if desc.run ~= nil then if desc.run ~= nil then
result = desc.run(msg, matches) result = desc.run(msg, matches)
print(" sending", result) -- print(" sending", result)
if (result) then if (result) then
_send_msg(receiver, result) local result2 = do_lex(msg, result)
if (result2 == nil) then
result2 = result
end
_send_msg(receiver, result2)
return return
end end
end end

View File

@ -10,6 +10,17 @@ else
_values = json:decode(c) _values = json:decode(c)
end end
function fetch_value(chat, value_name)
if (_values[chat] == nil) then
return nil
end
if (value_name == nil ) then
return nil
end
local value = _values[chat][value_name]
return value
end
function get_value(chat, value_name) function get_value(chat, value_name)
-- If chat values is empty -- If chat values is empty
@ -40,11 +51,27 @@ function run(msg, matches)
return get_value(chat_id, matches[1]) return get_value(chat_id, matches[1])
end end
function lex(msg, text)
local chat_id = tostring(msg.to.id)
local s, e = text:find("%$%a+")
if (s == nil) then
return nil
end
local var = text:sub(s + 1, e)
local value = fetch_value(chat_id, var)
if (value == nil) then
value = "(unknown value " .. var .. ")"
end
return text:sub(0, s - 1) .. value .. text:sub(e + 1)
end
return { return {
description = "retrieves variables saved with !set", description = "retrieves variables saved with !set",
usage = "!get (value_name)", usage = "!get (value_name)",
patterns = { patterns = {
"^!get (%a+)$", "^!get (%a+)$",
"^!get$"}, "^!get$"},
run = run run = run,
lex = lex
} }