How to lower all variants in a table?

I want to string.lower all my variants in my table and have that data saved.
Example:
Before:

local table = {
  ["Hello"] = "Hey",
  ["World"] = "Earth",
}

I want to change it to:

local table = {
  ["hello"] = "Hey",
  ["world"] = "Earth",
}

Is there any method of doing this? Here is my attempt:

local newArguments = {}
	local table2 = {}
	local Arguments = {
		["Hello"] = 1,
		["World"] = true
	}
	for i,v in pairs(Arguments) do
		i = string.lower(i)
	end
	for i,v in pairs(Arguments) do
		print(i)
	end

It doesn’t save the changed value in the table and ignores it.

1 Like

As for your code snippet above, when you call string.lower on the string of the key, you’re only changing the variable i - and not the table entry key.
To fix that, you can instead do something like:

Arguments[i] = nil -- First we remove the old entry, as we'll be assigning it again on the next line
Arguments[i:lower()] = v -- For a key 'Hello', i:lower() would be 'hello'. Now we've assigned the new entry.
If you have a nested table structure

In order to change all string keys in your table, you can use recursion - I doubt you have a recursive table (i.e. somewhere in your table where you refer back to a table that you’ve already visited when recursing through your table), but if you do, you can use a lookup table to make sure not to traverse tables you’ve already discovered.

An example of completing your problem here with nested table structures, the following code snippet can be used:

-- Implementation:
local function convertTableToLowercase(tabl)
  for key, value in next, tabl do
    tabl[key] = nil
    tabl[key:lower()] = value
    if type(value) == "table" then - there's a nested table here
        convertTableToLowercase(value)
    end
  end
end

-- Example usage:
local myTable = {
  HelloWorld = "Whoa!",
  NestedEntry = {
    MoreKeys = 9999,
    ALLUPPERCASE = true
  }
}

convertTableToLowercase(myTable)

--[[ Result of the above example:
{
  helloworld = "Whoa!",
  nestedentry = {
    morekeys = 9999,
    alluppercase = true
  }
}
]]
1 Like

Thank you a lot! I was spending a lot of time trying to figure it out.

I get this error again
My script:

for key,value in next, arguments do
		arguments[key] = nil
		arguments[key:lower()] = value
	end

Error:
Screenshot_302

Looks like due to us clearing the entry of the current spot in the table where the iterator (from using next, pairs or other methods of iterating over a table) is, it’ll break down - because normally, reaching a nil value means that the iterator is done.

To fix that issue, I’ve made a function here to create a new table and populate it with the lowercase keys instead, so we avoid that concurrency problem.

local function convertTableToLowercase(tabl)
  local t = {}
  for key, value in next, tabl do
    t[key:lower()] = value
  end
  return t
end

-- Example usage:
arguments = convertTableToLowercase(arguments)
2 Likes