This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
GAsplund's profile picture

Print a part of a string

Started by GAsplund, 10 January 2015 - 01:21 PM
GAsplund #1
Posted 10 January 2015 - 02:21 PM
Hey there!

I decided to make a joke program, AKA a Commodore 64 program. I have ran into a problem though, I can't make it print a specific part of an input that the user makes.
You know the command print, it looks like this in the commodore 64 real interface:

You see, you put in
print "message"
and it will print what's inside the quotation marks. I would like it to print just that and have use for this for other commands as well. Could anyone tell me how to perform that?
Lignum #2
Posted 10 January 2015 - 05:26 PM
The simplest way to do it is to use patterns. If you know regex, you should be able to get familiar with them quite easily.

local input = read()
local pattern = "(%a+)%s-\"(.-)\""
local cmd,msg = input:match(pattern)

if cmd == nil then
  printError("invalid syntax")
  return
end

if cmd:lower() == "print" then
  print(msg)
end

I'll explain the pattern part, the rest should be comprehensible by itself.
So here's the pattern for reference, let's break it up into smaller parts:
(%a+)%s-"(.-)"

(%a+) - Match multiple alphanumeric characters and capture them (so that string.match returns them..)
%s- - Match multiple spaces, if any.
"(.-)" - Match anything surrounded by quotes, and capture it. Note that there are backslashes here in the code; it allows us to type a quote without ending the string.

If the match function has matched anything, it should return two values, cmd and msg, which are, well, the command and the message.
You may have noticed that this only parses lines that are shaped like this: (command) "(a message)"
If you want a different shape, I'm leaving that as an exercice for you.

Of course, this is not a very good way to parse a language. You should do it character-by-character if you're serious about it… but since you said that this is a joke program, it should suffice.