• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

String Pluralize/Singularize Functions

Apollos

Dude who does stuff
Joined
Apr 22, 2009
Messages
829
Solutions
123
Reaction score
655
Location
United States
I have written two functions to help convert between singular and plural forms of words, particularly for things like monster names. These functions are placed in the file "data/lib/core/string.lua". They can be used to convert all words in a string or just the last word, depending on the second parameter. While I have tested them and they work well for many cases, due to the way English is, they may not always be perfect. Anyways, hope you enjoy.

Lua:
local vowels = { "a", "e", "i", "o", "u" }

local function pluralizeWord(word)
    if word:match("f$") or word:match("fe$") then
        word = word:gsub("f$", "ves"):gsub("fe$", "ves")
    elseif word:match("ch$") or word:match("sh$") or word:match("s$") or word:match("x$") or word:match("z$") or
    (not string.contains(vowels, word:sub(-2, -2)) and word:match("o$")) then
        word = word .. "es"
    elseif not string.contains(vowels, word:sub(-2, -2)) and word:match("y$") then
        word = word:gsub("y$", "ies")
    else
        word = word .. "s"
    end
    return word
end

string.pluralize = function(str, deepPluralize)
    if deepPluralize then
        local newStr = ""
        for word in str:gmatch("%S+") do
            newStr = newStr .. pluralizeWord(word) .. " "
        end
        return newStr:sub(1, -1)
    else
        return pluralizeWord(str)
    end
end

Lua:
local function singularizeWord(word)
    if word:match("ives$") then
        word = word:gsub("ives$", "ife")
    elseif word:match("ves$") then
        word = word:gsub("ves$", "f")
    elseif word:match("shes$") or word:match("ches$") or word:match("ses$") or word:match("xes$") or word:match("zes$") or
    (not string.contains(vowels, word:sub(-4, -4)) and word:match("oes$")) then
        word = word:gsub("es$", "")
    elseif not string.contains(vowels, word:sub(-4, -4)) and word:match("ies$") then
        word = word:gsub("ies$", "y")
    else
        word = word:sub(1, -2)
    end
    return word
end

string.singularize = function(str, deepSingularize)
    if deepSingularize then
        local newStr = ""
        for word in str:gmatch("%S+") do
            newStr = newStr .. singularizeWord(word) .. " "
        end
        return newStr:sub(1, -1)
    else
        return singularizeWord(str)
    end
end
 
Last edited:
Back
Top