Jump to content




String.split in ComputerCraft?


  • You cannot reply to this topic
6 replies to this topic

#1 PixelFox

  • Members
  • 106 posts

Posted 20 January 2015 - 09:56 PM

Is there a way to split lines in a sentence or words in a line into a table?
e.x
local Sentence = "Hello, I like things."
local SentenceSplit = {String.Split(Sentence)}
print(SentenceSplitz[])
print(SentenceSplit[2])
- Thanks, Lightning

#2 KingofGamesYami

  • Members
  • 3,002 posts
  • LocationUnited States of America

Posted 20 January 2015 - 10:01 PM

Look at string.gmatch and patterns, you can accomplish this with those.

Sentance -> words

local s = "Hello, I like things." )
local words = {}
for word in s:gmatch( "%S+" ) do
  words[ #words + 1 ] = word
end
print( words[ 1 ] ) --#should print "Hello,"


#3 SquidDev

    Frickin' laser beams | Resident Necromancer

  • Members
  • 1,427 posts
  • LocationDoes anyone put something serious here?

Posted 20 January 2015 - 10:01 PM

I would suggesting looking at some of the implementations here.

The easiest is:

function string.split(str, sep)
  return {str:match((str:gsub("[^"..sep.."]*?"..sep, "([^"..sep.."]*?)"..sep)))}
end

To understand this I would suggest looking at Lua patterns.

Edit: Beat me to it Yami! :ph34r:

Edited by SquidDev, 20 January 2015 - 10:02 PM.


#4 PixelFox

  • Members
  • 106 posts

Posted 20 January 2015 - 10:07 PM

Squid Dev, You're Idea is much better IMO, It's a function and can be changed, And it's just Simple.

#5 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 20 January 2015 - 10:09 PM

Uh, you could easily make a function out of the gmatch method, and it's a significantly better way to do it.

#6 PixelFox

  • Members
  • 106 posts

Posted 20 January 2015 - 10:11 PM

Lyqyd, I don't know how to use gmatch. So it wouldn't help me.

#7 Dragon53535

  • Members
  • 973 posts
  • LocationIn the Matrix

Posted 21 January 2015 - 08:56 AM

View PostKingofGamesYami, on 20 January 2015 - 10:01 PM, said:

Look at string.gmatch and patterns, you can accomplish this with those.

Sentance -> words

local s = "Hello, I like things." )
local words = {}
for word in s:gmatch( "%S+" ) do
  words[ #words + 1 ] = word
end
print( words[ 1 ] ) --#should print "Hello,"
local function splitString(str)
  local words = {}
  for word in str:gmatch( "%S+" ) do
	words[ #words + 1 ] = word
  end
  return words
end
*GASP* It's suddenly a function

Edited by Dragon53535, 21 January 2015 - 08:56 AM.






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users