PDA

View Full Version : A Silly Coding Problem



S Ferguson
February 12th, 2013, 02:07
This might come across as being a bit trivial but it's causing me no amount of grief. How do you store an element from one list, in order to see if it happens to be in another? It seems the simplest problems....

Moon Wizard
February 13th, 2013, 07:12
I assume you are talking about Lua. Also, I'm not sure if I'm following your question, maybe an example would help?

In general, Lua does not have built in support for sets (which you may be referring to). I've seen some sample code online from people writing their own set code.

Regards,
JPG

S Ferguson
February 13th, 2013, 13:52
Suppose I have elements from a list {foo, bar} and another {aMember, bar, anotherMember}. I want to hold and check whether foo is in the list, which would return false so MyAction1 doesn't occur, and then bar which should return true in which MyAction does take place.

And yes, it is Lua code. (I can't believe I forgot to put that in my original post), and it is a set problem (one I thought I left behind in University, but here it is again) ;)

S Ferguson
February 13th, 2013, 15:05
And although Lua doesn't support sets at a first-class data type, tables implement them quite nicely e.g. foo = {"one", "two", "three"} is basically a set with three string members in it.

S Ferguson
February 13th, 2013, 15:12
Okay. Ignore the preceding posts. I figured it out.

Trenloe
February 13th, 2013, 15:26
Gonna tell the community how you did it?

S Ferguson
February 13th, 2013, 16:12
Sure. Always willing to share.;)

The way Lua stores "sets" is through "pairing" the members of a list, with indices. Say we have aSet = {"foo", "bar"}. In this case index 1 = foo and index 2 = bar. From here we can take a temporary variable and assign, for example, aTemp = set[i], where i will be the element in that position in the array.

Now suppose you have a list anotherSet = {"one", "two", "bar"}. Nesting loops with the outer loop controlling the first indices in set, and the inner loop controlling the indices in anotherSet, you can effectively check member vs member in the fashion I wanted.

By way of example. on the first iteration "foo" from aSet would fail because it's not equivalent to any member of anotherSet, and on the 2nd iteration of the outer loop "bar" from aSet will succeed on the 3rd iteration of the inner loop, as it will be equivalent to "bar" in anotherSet.

Since all sets are finite, the iterators can be set to run from 1 to table.getn(someTable) which returns the number of elements in the "table" or set.

This explanation was brought to you by the letters o, t, h, and the number 3. :)(Which is what I probably was watching with my nieces when this problem arose):D

S Ferguson
February 13th, 2013, 16:58
Oh and there is always the "contains" function in the undoctored manager_string that is called by contains(item, set).