Using the `in` keyword instead of table.find()

In Python, stuff like this is possible:

if Something in {"1", "2"}:
    print("contains!")

However, in Lua, it’s this:

if table.find({"1", "2"}, Something) then
    print("Contains!")
end

What I’m suggesting here:

if "Example" in {"Example", "Not the string"} then
    print("Found!")

The nature of Lua is different so I am not suggesting to make it like Python, but please make in functional in the same sense. In works like this now:

for this, that in ipairs(table)

Python also has this:

for item in list:

I think if the in keyword were given multiple uses like in Python, it would help a lot more with quick debugging (wouldnt have to write a long function call under table) and general simplicity and cleanliness.

10 Likes
local h = {1, 2, 3}

for _,v in h do
-- whatever
end

This works. I’m not sure if it’s advised to use ipairs or pairs anymore.

EDIT: I like your example of if x in y though. I think that would be a good addition.

1 Like

For a few years I thought pairs returned key, value and ipairs meant iterator pairs and returned iterator, value but either that assumption was totally wrong or ipairs is just broken.

> for k, v in ipairs({["hi"] = 1}) do print(k, v) end
-

ipairs strictly only traverses values with numerical indices; it doesn’t work on keys that are anything other than a number:

local t = {
   ["hi"] = 1,
   3,
   2,
}

for i, v in ipairs(t) do
   print(i, v)
end
-- prints:
-- 1 3
-- 2 2
2 Likes

I don’t think this is a feature that the Luau team would consider adding because the use cases are niche (it is literally a substitute for table.find) and it complicates the language’s syntax. Python has it because the language was designed to be concise, but Luau was designed to be fast and simple. There is nothing wrong with using table.find right now so there is no incentive to modify it. You can see their RFC guidelines here: GitHub - luau-lang/rfcs: RFCs for Luau evolution

You can find other examples of features being turned down either because the feature won’t be that practical or an alternative is already available:

Also, another way of doing what you wanted could be with dictionaries/hashmaps:

if hashmap[something] then
if ({[1]=true, [2]=true}) [something] then
4 Likes

Pluto is a Lua dialect which has feature. I think in should be an operator and still keyword. as an operator it should be compiled to table.find, or maybe in the future an equivalent for strings.

3 Likes

I can understand simple. But this feature will have no effect on performance, it is just shorthand for table.find.

To be honest I forgot about strings. If we’re chewing out table.find, making in a replacement to string.find also makes a lot of sense. in as an operator makes sense syntactically (python just does it well), and while table.find works ok, it would be best for this to be added

3 Likes