I've been looking over some code lately and I've been trying to understand what args means. I know it stands for 'arguments' (At least I think). I noticed that args are for what the user puts in, but I don't know how to put everything together.
def run(self): while True: command = raw_input('> '); self.parse(command)
def parse(self, command): comm = command.lower().split(' ') try: cmd = comm[0] except IndexError: cmd = 'help' try: args = comm[1:] except IndexError: args = [] try: result = getattr(self.cmd, cmd)(' '.join(args).strip()) except AttributeError: result = 'Unknown Command' print result
comm is turned into a list of all the words in the string.
comm = command.lower().split(' ')
This splits up the string "command" with the space delimiter, and turns everything to lowercase.
cmd = comm[0]
This sets cmd to the first element of the string. So, an example "look davion" comm[0] will be "look" and comm[1] will be "davion"
try: args = comm[1:] except IndexError: args = []
This is where args is initialized. If comm is only one element (eg. someone types in just 'look') then comm[1:] will throw an exception (IndexError). If that happens it just sets it to an empty list.
Note that this only splits based on single spaces. More complex parsing will generally check for quotes and other special characters.
This works for things like "get apple" or "kill fat troll", but not for things like "cast 'molten lava' bugbear". Of course, you are free to eschew the typical Dikuesque parser and use something more like infocom's…. "cast molten lava at the green bugbear behind the tree". :)