From d185f096ff8d9843c6ba48484c6dcc2c075866b3 Mon Sep 17 00:00:00 2001 From: Abigail Date: Wed, 10 Feb 2021 19:55:55 +0100 Subject: Lua solution for week 99, part 1 --- challenge-099/abigail/README.md | 1 + challenge-099/abigail/lua/ch-1.lua | 47 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 challenge-099/abigail/lua/ch-1.lua diff --git a/challenge-099/abigail/README.md b/challenge-099/abigail/README.md index 3e98f336de..159a51bf25 100644 --- a/challenge-099/abigail/README.md +++ b/challenge-099/abigail/README.md @@ -42,6 +42,7 @@ Output: 1 ### Solutions * [AWK](awk/ch-1.awk) * [C](c/ch-1.c) +* [Lua](lua/ch-1.lua) * Perl * [Using regular expressions](perl/ch-1.pl) * [Recursion](perl/ch-1a.pl) diff --git a/challenge-099/abigail/lua/ch-1.lua b/challenge-099/abigail/lua/ch-1.lua new file mode 100644 index 0000000000..fc40672471 --- /dev/null +++ b/challenge-099/abigail/lua/ch-1.lua @@ -0,0 +1,47 @@ +#!/opt/local/bin/lua + +-- +-- See ../README.md +-- + +-- +-- Run as: lua ch-1.lua < input-file +-- + +for line in io . lines () do + -- + -- Extract the string and pattern + -- + local str, pattern = line : match ("(%S+) +(%S+)") + + -- + -- Turn the pattern into a Lua pattern, replace any + -- character c: + -- if c == "?" -> . + -- if c == "*" -> .* + -- if c is not an alpanum -> %c + -- otherwise, keep c as is + -- And then add anchors + -- + pattern = pattern : gsub (".", function (c) + local result = c + if c == "?" then + result = "." + elseif c == "*" then + result = ".*" + elseif c : match ("%W") then + result = "%" .. c + end + return result + end) + pattern = "^" .. pattern .. "$" + + -- + -- Print 1/0 depending whether we have a match or not. + -- + if (str : match (pattern)) then + print (1) + else + print (0) + end +end -- cgit