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

Patterns ([^<sign>])

Started by Lolgast, 21 May 2012 - 07:59 AM
Lolgast #1
Posted 21 May 2012 - 09:59 AM
I'm trying to make tables into strings, and vice versa, for sending coördinates trough the rednet. I know you can make tables into strings with str = table.concat(table, sep), and then look for the sep when making it into a table again. But, I want "–" as sep, and I then I want to look for a substring ending with –. If you had a sep like "," you could use
string.find(str, '(.-)[^,]')
But now I have – as sep, so I want to look for – and not -. If you use
string.find(str, '(.-)[^--]')
It will look for a substring ending in - or ending in -, right? So, what I was wondering, is there a way to find a substring ending in –? P.S. I don't have a computer with minecraft/computercraft right now, so I have no possibility to test it ingame right now.
Luanub #2
Posted 21 May 2012 - 11:08 AM
Here's the way I used to do it, I used a comma as my seperator so you can just modify it for the –'s

Spoiler

function pattern(text,pattern,start)
return string.sub(text,string.find(text,pattern,start)) end
	
function getSeperated(string)
local sep = {}
local done = false
local count,prevVars,tmp = 0,0,0
string = string..",|"
while not done do
  count = count + 1
  tmp = pattern(string,"[^,]+",count+prevVars)
  if tmp == "|" then done = true return sep end
  prevVars = prevVars + tmp:len()
  table.insert(sep,count,tmp)
end
return sep
end

However its probably easier to just use textutils.serialize() and textutils.unserialize()


string = textutils.serialize(table)
table = textutils.unserialize(string)
Lolgast #3
Posted 21 May 2012 - 11:56 AM
However its probably easier to just use textutils.serialize() and textutils.unserialize()


string = textutils.serialize(table)
table = textutils.unserialize(string)
Yeah, but I like to do it the hard way ;P
But I'll try this back home, where I have mine-/computercraft. I also have an other idea, will test whether that works too.
MysticT #4
Posted 21 May 2012 - 08:26 PM
If you still want to use a separator, you can use this pattern:

string.find(s, "(.*)%-%-")
It would search for a substring containing zero or more characters followed by –
You could loop through every substring with:

for s in string.gmatch(str, "(.-)%-%-") do
  -- do something with the substring s
end
Lolgast #5
Posted 22 May 2012 - 12:08 PM
Ah, yeah. That's what I was looking for. Bit weird I didn't come up with that by myself, but well. Now I know it too.
kazagistar #6
Posted 22 May 2012 - 01:06 PM
Only thing serialize does not handle is if you have one table inside another table in multiple locations. That would take quites some effort to fix, however. Also functions and metatable and stuff, but you gotta know your limits. :P/>/>