Search code examples
stringlualua-tablelowercase

Lower case a table in lua


Monster_List = {'Hunter','creature','demon'}

Monster_List = Monster_List:lower()

and what about

Attacks = {}

Attacks[1] = {'CreaTurE','MonstEr'}
Attacks[2] = {'FrOG', 'TurtLE'}

I'm sorry if this seems way too stupid, but how do I lowercase all contents of a table?

Edit: as for the second question, i did it like this, not sure if correct

for i=1,#Attacks do
    for k,v in pairs(Attacks[i]) do
    Attacks[i][k] = v:lower()
    end
end

Solution

  • Iterate the table and update the values.

    lst = {'BIRD', 'Frog', 'cat', 'mOUSe'}
    for k,v in pairs(lst) do
        lst[k] = v:lower()
    end
    
    table.foreach(lst, print)
    

    Which yields:

    1   bird
    2   frog
    3   cat
    4   mouse
    

    to handle nested tables, a recursive function would make it a breeze. something like this?

    lst = {
        {"Frog", "CAT"},
        {"asdf", "mOUSe"}
    }
    
    function recursiveAction(tbl, action)
        for k,v in pairs(tbl) do
            if ('table' == type(v)) then
                recursiveAction(v, action)
            else
                tbl[k] = action(v)
            end
        end
    end
    
    recursiveAction(lst, function(i) return i:lower() end)
    -- just a dirty way of printing the values for this specific lst
    table.foreach(lst, function(i,v) table.foreach(v, print) end)
    

    which yields:

    1   frog
    2   cat
    1   asdf
    2   mouse