0 Replies - 1068 Views - Last Post: 29 May 2010 - 02:11 PM

#1 athlon32  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 117
  • View blog
  • Posts: 363
  • Joined: 20-August 08

[LUA]String Iterator Function

Posted 29 May 2010 - 02:11 PM

Description: Should work with Lua 5.1By default, Lua has no way to iterate over strings—like other languages. This handy function allows you to do that.
-- A custom iterator function to be used in loops.
-- It employs a closure, and upon each call returns 
-- a one character sub-string of ever increasing
-- position. 
function chars (t)
    local j = 0;
    local s = #t; -- Get string length

    return function ()
        j = j + 1;
        if j <= s then 
            return t:sub(j,j);
        end
    end
end


-- Below is an implementation. Ignore it if
-- you don't give concern.

-- This function is only used in the loop
-- but it might be useful elsewhere. You
-- can use it if you care. :)
local function isvowel(t)
    local s = t:upper();
    if s == "A" or s == "E" or s == "I" or
         s == "O" or  s == "U" then
        return true;
    end

    return false;
end

local word = "Onomatopoeia"
local vowelcount = 0;

for c in chars(word) do
    if isvowel(c) then
        vowelcount = vowelcount + 1; 
    end
end

print("There are " .. vowelcount .. " vowels in the word " .. word);



Is This A Good Question/Topic? 0
  • +

Page 1 of 1