So lets say I have a table
local s = {
Common = 5,
Uncommon = 10
}
print(table.find(s, "Common")) --> nil
-- However print(s["Common"]) will work
Can someone explain why and how to fix
So lets say I have a table
local s = {
Common = 5,
Uncommon = 10
}
print(table.find(s, "Common")) --> nil
-- However print(s["Common"]) will work
Can someone explain why and how to fix
table.find looks for any value in a table, not a dictionary. As for that you can just call the dictionary’s value directly and it would work 1:1 like table.find. Just like in the example you gave.
table.find
searches by value and returns the index where it was found:
-- Lua/Luau equivalent:
local s = {
Common = 5,
Uncommon = 10
}
for index, value in s do
if value == "Common" then
return index
end
end
Basically, what @awry_y said
Like? I dont understand
print(table.find(s, 5))
Wont work too
So I just have to do like this?
print(s["Common"])
Also I wonder if that above will error if there no such value (Like if table exists but there no common) or it will return nil
Yes I know that this will work too, but it takes 4 lines
It would just return nil. Though, if you try to use it then it would error. You can also set it like:
s.Common = 5
It won’t as 5 is the value of a key in the dictionary. You can’t access the value without a key. The key, is the name of the dictionary.
Oh, ok, I got it then ( I mean I was always using table[“Something”] to get value of it, but wondered how table.find works). Thanks
I was showing what it does internally
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.