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

Patterns question

Started by Dragon53535, 11 April 2017 - 09:23 PM
Dragon53535 #1
Posted 11 April 2017 - 11:23 PM
Hello guys. It's been a long time since I actually was on this forums, and even longer than when I was actually active. The question I'm posing today is more of a general Lua question as opposed to a CC question as I'm asking this question for a project that is unrelated to CC in any way, besides Lua that is.

I'm mostly just asking this question here as the resources online aren't always the best at finding pertinent information for patterns, and I respect your guy's knowledge on Lua.

So the question today is how might I possibly achieve a ReGex's '|' operator in patterns. I've read it cannot be done in patterns themselves, so I'm gonna pick your brains on it.

The reason for this is that I'm matching console input that is able to be formatted like

arg1 arg2 "this is arg3" arg4 "another arg that is arg5"
And so on.

I can easily do this on my own without messing with patterns, but I'd rather my code not to be too long if there's a way to bypass that restriction.


Soo yeah, here's hoping I don't have to take too much time to develop the solution and can instead use a different avenue.
Dragon53535 #2
Posted 12 April 2017 - 12:24 AM
Currently I have this bit of code for splitting in that fashion that works:


local function breakArgs(str)
  local strTbl = {}
  while #str > 0 do
	local a = str:find(' ')
	local b = str:find('"')
	local didQuote = false
	if b and b > 0 and (not a or b < a) then
	  local b2 = str:sub(b+1):find('"')
	  if b2 and  b2 > 0 then
		didQuote = true
		table.insert(strTbl,str:sub(b+1,b2))
		str = str:sub(b+b2+2)
	  end
	end
	if not didQuote and a and a > 0 then
	  table.insert(strTbl,str:sub(1,a-1))
	  str = str:sub(a+1)
	elseif not didQuote then
	  table.insert(strTbl,str)
	  break
	end
  end
  return strTbl
end

Hmm, on thinking. I should probably add a space check at the end of the quote…

I used a Regex lib to do it, but I'm still curious of how to do it easily in native lua.
Edited on 11 April 2017 - 11:51 PM
Bomb Bloke #3
Posted 12 April 2017 - 03:07 AM
FWIW, here's how CraftOS does it.