Created
April 26, 2017 16:01
-
-
Save imliam/3b18b5a5baad530dbdf0312d91a0b1b5 to your computer and use it in GitHub Desktop.
Command line argument parsing
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
command_strings = { | |
'php artisan make="hi mate" heh "I have a value"', | |
"php artisan make:auth", | |
[[I "am" 'the text' and "some more text with '" and "escaped \" text"]], | |
[[1 2 word 2 9 'more words' 1 "and more" "1 2 34"]], | |
[[omo "This is a string!" size=14 font="Comic Sans" break= hmm "thing and 'thing'" ]] | |
} | |
function command_parse(s) | |
local t={} | |
local n=0 | |
local b,e=0,0 | |
while true do | |
b,e=s:find("%s*",e+1) | |
b=e+1 | |
if b>#s then break end | |
n=n+1 | |
local until_next_space = s:sub(b, s:find("%s",b)) | |
if until_next_space:find('="') then | |
local equals = s:find('="', b) | |
local endofstring = s:find('"', equals+2) | |
t[s:sub(b, equals-1)] = s:sub(equals+2, endofstring-1) | |
b, e = b, endofstring+1 | |
elseif until_next_space:find("='") then | |
local equals = s:find("='", b) | |
local endofstring = s:find('"', equals+2) | |
t[s:sub(b, equals-1)] = s:sub(equals+2, endofstring-1) | |
b, e = b, endofstring+1 | |
elseif s:sub(b,b)=="'" then | |
b,e=s:find(".-'",b+1) | |
table.insert(t, s:sub(b,e-1)) | |
elseif s:sub(b,b)=='"' then | |
b,e=s:find('.-"',b+1) | |
table.insert(t, s:sub(b,e-1)) | |
else | |
b,e=s:find("%S+",b) | |
local tmp = s:sub(b,e) | |
if tmp:find('=') then | |
t[tmp:sub(0, tmp:find('=') - 1)] = tmp:sub(tmp:find('=') + 1, -1) | |
else | |
t[s:sub(b,e)] = {} | |
end | |
end | |
end | |
return t | |
end | |
function execute_parsed_command(command) | |
local cmd = command:sub(0, command:find("%s")-1) | |
local args = command:sub(cmd:len()+2) | |
t=command_parse(args) | |
if cmds[cmd] then | |
cmds[cmd](t) | |
end | |
end | |
cmds = { | |
php = function(t) | |
print("Ay this is an executed php command.") | |
if t['artisan'] then | |
print('Artisan') | |
end | |
if t[1] then | |
print('I have a value') | |
end | |
end | |
} | |
for key, command in pairs(command_strings) do | |
execute_parsed_command(command) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment