Jump to content




reading pieces of/splitting a string


5 replies to this topic

#1 uh20

  • Members
  • 11 posts

Posted 30 January 2013 - 03:02 AM

hey, ive been having troubles splitting a line from file:read() into pieces (basically i want to know how to edit a string)

for example, how would you split this
line = "12345678"
value[1] = "12"
value[2] = "34"
value[3] = "56"
and so on...

this seems like an easy thing to do, but the search engines have dubiously failed to return any answers.
thanks in advance.

#2 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,459 posts

Posted 30 January 2013 - 03:42 AM

Split into new topic.

#3 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 30 January 2013 - 03:43 AM

To extract characters when when know where they will be
local s = "This is a string"
print( string.sub( s, 2 ) )	 -- Output: his is a string
print( string.sub( s, 2, 6 ) )  -- Output: his i
print( s:sub( 2, 6 ) )		  -- Output: his i
NOTE: The 3rd code example does the same as the second, its just written differently

To get the parts of a string when the only thing we know is a common character
function split( str, regex )
  local t = { }
  local fpat = "(.-)"..regex
  local last_end = 1
  local s, e, cap = str:find(fpat, 1)
  while s do
	if s ~= 1 or cap ~= "" then
	  table.insert(t,cap)
	end
	last_end = e+1
	s, e, cap = str:find(fpat, last_end)
  end
  if last_end <= #str then
	cap = str:sub(last_end)
	table.insert(t, cap)
  end
  return t
end

local s = "This is a string"
local tableOfParts = split( s, " " )
This will give us a table containing the following data
"This"
"is"
"a"
"string"

the basics of this one is it goes through the string looking for the pattern suppled, when found it will add the string between those patterns and add them to a table. certain characters like "." require a % in front making the search pattern "%."

Edited by TheOriginalBIT, 30 January 2013 - 03:46 AM.


#4 uh20

  • Members
  • 11 posts

Posted 01 February 2013 - 03:00 AM

OK
i thought string.sub only did substitutions, guess it can also read specific parts of a line as well

#5 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 01 February 2013 - 03:03 AM

no string.sub doesn't do substitutions. thats string.gsub. string.sub stands for string.substring

string.sub("hello",3) is from the 3rd character to the end ("llo")
string.sub("hello",3,4) is from the 3rd to the 4th character ("ll")
string.sub("hello",3,3) is the 3rd character in the string ("l")

More info can be found here: http://lua-users.org...LibraryTutorial

#6 uh20

  • Members
  • 11 posts

Posted 01 February 2013 - 03:10 AM

ok, thats what i got mixed up them ;)
was needing this for reading a reboot-file, so the computer can tell what storage carts where after turning off.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users