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

Test if String is Enclosed

Started by PixelFox, 15 January 2016 - 08:56 PM
PixelFox #1
Posted 15 January 2016 - 09:56 PM
I'm making an IDE for my programming language, and the variables are enclosed in two Carets (or the symbol ^), I would like to change their color.
I have never been very good with Patterns, so I would like to know what Pattern I could use to see if a word (ex. Var) has Carets around it (ex. ^Var^). You're input will be very useful.



Thanks - Lightning.
Edited on 15 January 2016 - 09:14 PM
Ajt86 #2
Posted 15 January 2016 - 10:12 PM
Lua doesn't use regular expressions, it uses patterns.
PixelFox #3
Posted 15 January 2016 - 10:14 PM
Yeah, that's what I mean. Sorry about that, I'll change it.
Dragon53535 #4
Posted 15 January 2016 - 10:40 PM
To get the location in the string of the variable name's start and stop positions.

local startNum = string.find(str,"%^%w+%^") + 1
local endNum = string.find(str,"%^",startNum) -1
That will get you the first letter of the variable name, and the last letter of the variable name.

To find every occurrence and change the color of each variable name would require a few loops, one to loop through and gather each of the start and end positions and post them into a table. And another to loop through the table, and print in sequence up to the saved numbers, change the text color, write the variable name, change the color back, and be able to continue until every variable name is written. I'll leave that bit up to you, but this should work easily for your needs.
PixelFox #5
Posted 15 January 2016 - 11:24 PM
That's not what I mean, the string is not like that. It's an array of words.
Dragon53535 #6
Posted 15 January 2016 - 11:29 PM

if string.sub(str,1,1) == "^" and string.sub(str,#str,#str) == "^" and not ( string.find(str," ") ) then
If word has first character as ^ and last character as ^ and has no spaces then
Or to also include the earlier post


local startNum = string.find(str,"%^%w+%^")
local endNum
if startNum then
  endNum = string.find(str,"%^",startNum + 1)
end
if endNum then
  endNum = endNum - 1
  startNum = startNum + 1
  --# BAM it's enclosed in ^'s
end
Or hell, if you just want the pattern to know if it's in the string:


local isThere = string.match(str,"%^%w+%^")
if isThere then
  --#Do stuff
end
Edited on 15 January 2016 - 10:33 PM
PixelFox #7
Posted 15 January 2016 - 11:32 PM
Okay, thanks!
Edited on 15 January 2016 - 10:36 PM