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

String.split in ComputerCraft?

Started by PixelFox, 20 January 2015 - 08:56 PM
PixelFox #1
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
KingofGamesYami #2
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,"
SquidDev #3
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 on 20 January 2015 - 09:02 PM
PixelFox #4
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.
Lyqyd #5
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.
PixelFox #6
Posted 20 January 2015 - 10:11 PM
Lyqyd, I don't know how to use gmatch. So it wouldn't help me.
Dragon53535 #7
Posted 21 January 2015 - 08:56 AM
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 on 21 January 2015 - 07:56 AM