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

Empty Pattern in my Split function

Started by Wing, 01 March 2013 - 09:00 AM
Wing #1
Posted 01 March 2013 - 10:00 AM
Hey guys, I brought this up inside another one of my threads but here it is again.
When I leave the <pat> empty ("") it returns an empty table, I'm hoping for it to split each letter up and not nothing…

function split(str,pat)
local t = {}
local fpat = "(.-)" .. pat
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
Lyqyd #2
Posted 01 March 2013 - 11:54 AM
Use this instead: "."

The period is a special operator for patterns that matches any single character.
Bubba #3
Posted 01 March 2013 - 01:36 PM
I'm confused by what you want. Do you want this function to split the string into separate characters if pat is left empty? If so then there is a handy function called string.gmatch(pat).

local example = "This is a string of characters"
local tExample = {}
for char in example:gmatch(".") do
  table.insert(tExample, char)
end
Now tExample has every character in example seperated.
Wing #4
Posted 01 March 2013 - 01:37 PM
Alright, lets try that, will edit the post with the results!
Wing #5
Posted 01 March 2013 - 02:10 PM
Ok well, "." didn't work….
command: textutils.serialize(w.split("lol I Win", "."))
returns: {[1]= "", [2]="", [3]="", [4]="", [5]="", [6]="", [7]="",}
Lyqyd #6
Posted 01 March 2013 - 03:19 PM
Don't use that split function. This should do the trick:


function stringToCharTable(str)
  local tab = {}
  for i = 1, #str do
    tab[i] = string.sub(str, i, i)
  end
  return tab
end
Wing #7
Posted 02 March 2013 - 09:06 AM
Thanks I'm sure that works I'll add it, but I still want to know why this isn't working, using 2 different function to split strings is weird, but will have to do!