Character count in Lua

function char_count(str, char) 
    if not str then
        return 0
    end

    local count = 0 
    local byte_char = string.byte(char)
    for i = 1, #str do
        if string.byte(str, i) == byte_char then
            count = count + 1 
        end 
    end 
    return count
end

print(char_count("aa aahh a", "a"))
print(char_count("", "a"))
print(char_count("aloha", "a"))
Code · Tips 20. Aug 2009
© Amir Salihefendic. Powered by Skeletonz.