If you want to have it like, you give the function a key (eg: Apple) and you want the value (eg: 10) you could make your function simply like this:
local t = {apple = 10, orange = 5}
local function getValue(key)
for i, v in pairs(t) do
if i == key then
return v
end
end
end
print(getValue("apple")) <-- Should print 10
local t = {apple = 10, orange = 5}
local function getValue(key)
local i = 1
for k, v in pairs(t) do
i = i + 1
if i == key then
return {
key = k,
value = v
}
end
end
end
print(getValue(1)) --> returns a table with the key and value
Won’t be in the same order all the time, but basically works the same way. It’s impossible to have a dictionary ordered the same without some array to show the original order of the dictionary.
Regardless of the fact that you can only access indexes a certain way depending on the way you define them, it (to an extent but not exactly) would be possible if you could traverse dictionaries according to apparent visual order, which you cannot.
You can however change that to an array (containing dictionaries) :
local t = {{apple = 10}, {orange = 5}};
local t2 = t -- let __index fire for every index
t = setmetatable({}, {__index = function(self, k)
local v = t2[k] -- prevent C stack overflow
local ind = next(v)
return v[ind]
end}
)
-- the way this is set up, it returns just the value like your requirement...
-- but you'll be forced to define only one ind+val pair in each entry ({})
print(t[1]) --> 10
print(t[2]) --> 5
I’ll add on to this method, you can also have a reverse lookup table. You can set it up like this,
local t = {apple = 10, orange = 5}
local reverseTable = {}
for key, value in pairs(t) do
reverseTable[value] = key
end
print(reverseTable[10]) --> apple
You are doubling memory this way but it has its uses. A lot of good ideas in this thread for how to go about it.
I didn’t forget to do it I didn’t mean to there’s no use for it.
There’s no need to use rawget there when you know v[ind] won’t trigger any written code bound to __index anyway, also owing to the nature of this solution you’re restricted to having to index in a way that won’t cause issues for the system’s design.
I only used rawget in the beginning so we don’t end up with an infinite __index.
This time you’re right I probably forgot what I was doing, failed to notice it at the time of responding before because I made the mistake of bothering to reply without understanding my code.
But then again what’s the point in bumping a topic just to point out an unnecessary line of code? DM’ing me would’ve resulted in the same outcome.
local function GetKeyName(Table, Index)
if typeof(Table) == "table" and typeof(Index) == "number" then
local TableIndex = 0
for Key, Value in pairs(Table) do
TableIndex = TableIndex + 1
if TableIndex == Index then
return Key
end
end
end
end