Thursday, October 14, 2010

Splitting text into individual letters

One Lua trick that I use a lot is taking a string and splitting it up into individual characters which then get stored in a table.

I used this approach for my circle writing function and many other functions. This is how it's done.

You need the following function in the Lua script above the main function. I did not write this function and I cant remember exactly where I got it from but whoever did write it has my thanks!

function string:split(delimiter)
local result = { }
local from = 1
local delim_from, delim_to = string.find( self, delimiter, from )
while delim_from do
table.insert( result, string.sub( self, from , delim_from-1 ) )
from = delim_to + 1
delim_from, delim_to = string.find( self, delimiter, from )
table.insert( result, string.sub( self, from ) )
return result

These are the lines that split up the text...
print (text) --> text

sub=string.gsub(text, ".", "%1|")
-- the above inserts "|" after every character
print (sub) --> t|e|x|t|

split=string.split(sub, "|")
-- the above splits the string whenever a "|" occurs and also deletes the "|"
the resulting split up characters are stored in a table called split in this case

-- slen is the length of the original text,
so will be the number of entries in that table "split"

so that:
split[1] = "t"
split[2] = "e"
split[3] = "x"
split[4] = "t"

now I can deal with each character individually.
I could give each character a different font, or a different color
or, in the case of my square font conky below, convert each character to the square font.

No comments:

Post a Comment