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

[patterns] Capturing Too Much Info

Started by Engineer, 26 October 2013 - 08:02 AM
Engineer #1
Posted 26 October 2013 - 10:02 AM
Hello,

Im trying to write something that can map a table out of a string. I have come pretty far as patterns go, but I have found one major flaw with it. First, here is the function that I wrote and the 'stringed table' Im using for test purposes.

The code

local function mapTable( sTable )
	local strippedOf = sTable:gsub( "{%s*", "" )
							 :gsub( "%s*}", " " )
	
	-- Retrieve decimal indices
	local decimal = {}
	for index, value in string.gmatch( strippedOf, "%[(%d+)%]%s*=%s*(.+)[,;%s]+" ) do
		print( string.format( "[%s] = %s\n", tostring(index), tostring(value) ))
		table.insert( decimal, { index, value })
	end

	-- Retrieve string indices
	local String = {}
	for index, value in string.gmatch( strippedOf, "([%a_]+)%s*=%s*(.+)[,;%s]+" ) do
		print( string.format( "%s = %s\n", index, value ))
		table.insert( String, {key, value})
	end

	-- Retrieve ["key"] indices
	local stringBracket = {}
	for index, value in string.gmatch( strippedOf, "%[[\"\'](.+)[\"\']%]%s*=%s*(.+)[,;%s]+" ) do
		print( string.format( "[%q] = %s\n", index, tostring(value) ))
		table.insert( stringBracket, { index, value })
	end
end

mapTable( "{ [\"test\"] = \"cool\", testing = \"haha\", [1] = \"testmuch,\" }" )

I am printing everything out, just for test purposes. Here is the output Im getting:


As you can see, it works kinda. But Im expecting:

[1] = "testmuch," --# Works! :D/> Just because its the last index

testing = "haha"  --# Doesnt work unfortunately

["test"] = "cool" --# Doesnt work unfortunately

I know it is caused in each pattern by the last (.+). But I am unsure how to fix it properly.

If anything is unclear, please ask! And thanks for trying to help me.
- Engineer
sens #2
Posted 26 October 2013 - 12:40 PM
Okay, after reading the entire post, I suggest the following patterns:


--# Retrieve decimal indices
"%[(%d+)%]%s*=%s*(.-)%s*[,;?]%s*"

--# Retrieve string indices
"([%a_]+)%s*=%s*(.-)%s*[,;?]%s*"

--# Retrieve ["key"] indices
"%[[\"\'](.+)[\"\']%]%s*=%s*(.-)%s*[,;?]%s*"

Fieldsep characters (comma or semicolon) in quotes will probably break the string now. Maybe someone else can help with that.
Engineer #3
Posted 26 October 2013 - 02:04 PM
However the pattern kinda works, sens, I think Im going to try another startegy. Because I dont know any other way of doing it with patterns. Maybe someone else knows, but a different strategy can also be good, I think.

I will edit or post a new post after I have tried other strategies.