little piece of script to split a string into an array/table

Share your scripts and packages with other Mudlet users.
Post Reply
kakku
Posts: 42
Joined: Tue Feb 22, 2011 12:03 pm

little piece of script to split a string into an array/table

Post by kakku »

found this nice function somewhere on the net, thought it was usefull enough to share.
Code: [show] | [select all] lua
function splitToArray(str, c)
local a = string.find(str, c)
local str = string.gsub(str, c, "", 1)
local aCount = 0
local start = 1
local array = {}
	while a do
	array[aCount] = string.sub(str, start, a - 1)
	start = a
	a = string.find(str, c)
	
	str = string.gsub(str, c, "", 1)
	aCount = aCount + 1
	end
return array
end
str is the string you want to split and c is the character you want to split it by.

so if you have a
stringName = "N E S W "
. and you want it turned into a array/table you do
tableName = splitToArray(stringName, " ")
and it returns a nice table/array :)

only downside is that you need to add an extra chracter to split on or the last character will fall off..
so i added an extra space since that is what i'm splitting with
stringName = "N E S W".." "
maybe it could be improved but overall i think very usefull.

Post Reply