lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I've been browsing around looking for the best way to use lua tables
to represent lists where I can test for list membership.

In Python I can do something like:
a = "a"
if a in ["a", "b", "c"]:
    print "a is in the list"

It's easy to set up lua lists:
mylist = {"a", "b", "c"}
What I'm wondering is what is the design-intended best practice for
testing for list membership.  And what is the fastest way to do this?

Assuming that for-loops are run-time expensive for large lists, is
something like this considered good practice?
myList = {"a", "b", "cde"}
myListString = "|" .. table.concat(myList, "|") .. "|"
a = "cde"
if string.find(myListString, "|"..a.."|") then
    print("found!")
else
    print("not found")
end

One problem is that if the list contains mixed data this will not
work.  I suppose for a more generalized list like:
myList = {"a", "b", 1, 2, {3, 4}, function() print'hi' end }
all I can do is walk through the list with a for loop checking each
list item one at a time.

Thanks,
Bill