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

Extract two variables from one

Started by Microwarrior, 04 July 2015 - 10:50 PM
Microwarrior #1
Posted 05 July 2015 - 12:50 AM
Is there a way to take something like "data1|data2" and convert it to two different variables along the | symbol?
Lyqyd #2
Posted 05 July 2015 - 01:27 AM
You can use string.match. The pattern to use in this case would look something like "([^|])+|([^|])+".
cmdpwnd #3
Posted 05 July 2015 - 01:28 AM
Is there a way to take something like "data1|data2" and convert it to two different variables along the | symbol?

you can use a for loop which iterates over a delimiting character, in your case '|' and can assign any non-matching values to a new variable.



function separate(data)
  local matches = {}
  local a = 1
  for token in data:gmatch("[^|]+") do --iterate over any value that is NOT '|' (gmatch code []= custom pattern, ^=NOT |=delimiter we are using +=as many matches as possible)
	matches[a] = token
	a=a+1
  end
  print(table.unpack(matches))
end
Edited on 04 July 2015 - 11:43 PM
Bomb Bloke #4
Posted 05 July 2015 - 01:36 AM
Although, you're generally better off preventing the strings from being combined in the first place, if possible.
meigrafd #5
Posted 06 July 2015 - 12:47 PM
Im using an function for such:


function split(pString, pPattern)
	local Table = {}  -- NOTE: use {n = 0} in Lua-5.0
	local fpat = "(.-)" .. pPattern
	local last_end = 1
	local s, e, cap = pString:find(fpat, 1)
	while s do
		if s ~= 1 or cap ~= "" then
			table.insert(Table, cap)
		end
		last_end = e+1
		s, e, cap = pString:find(fpat, last_end)
	end
	if last_end <= #pString then
		cap = pString:sub(last_end)
		table.insert(Table, cap)
	end
	return Table
end

Usage:
message = "hello:world"
msgTable = split(message,"\:")
print(msgTable[1])
print(msgTable[2])

Source: http://stackoverflow.com/questions/1426954/split-string-in-lua
Edited on 06 July 2015 - 10:48 AM
Microwarrior #6
Posted 11 July 2015 - 06:26 AM
Thanks, this has all been very useful!