I felt like this could be done much more easily with the string library patterns, so I did that and also cleaned up some code I felt was dirty.
local args = {...}
local vowels = "AEIOUaeiou"
local function usageError()
error([[
Usage:
Code:
pig c [text]
Decode:
pig d [text]
Output is also saved to pig_out]])
end
if #args < 2 then
usageError()
end
local f = assert(fs.open(fs.combine(shell.dir(), "pig_out"), "w"))
local ow = write
local write = function(t)
f.write(t)
ow(t)
end
local mode = table.remove(args, 1)
local str = table.concat(args, " ")
if mode == "c" then
local s = str:gsub("(%A*)([^" .. vowels .. "']?)(%a+)",function(a,b,c)
if #b == 0 then
return a .. c:sub(2) .. c:sub(1,1) .. "way"
else
return a .. c .. b .. "ay"
end
end)
write(s)
elseif mode == "d" then
local s = str:gsub("(%A*)([%a']+)(ay)", function(a,b,c)
if b:find("[" .. vowels .. "]w$") == #b - 1 then
b = b:sub(1,-2)
end
return a .. b:sub(-1) .. b:sub(1,-2)
end)
write(s)
else
usageError()
end
print()
f.close()
EDIT: To add a bit more detail about what I changed, the pig_out file is now put in the shell.dir() directory, the program errors out when usage is wrong instead of just printing and returning (same effect, but this way if you're using a shell that handles errors differently, it's handled that way), the program errors out when file opening fails, apostrophe's are allowed in words, and it's set up so str = table.concat(args, " ") can be replaced with any means of getting a string with all the words and whitespace your heart desires. Oh and also it handles decoding words with a vowel at the beginning a little better. I can't think of a better way to make that perfect than to have a dictionary of real words, and at that point it's questionable whether that's faster than polling some site via http.