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.
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
}
}
]]
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)