Rapptz / sol

A C++11 Lua wrapper
MIT License
209 stars 32 forks source link

table.for_each for iteration #61

Closed ThePhD closed 9 years ago

ThePhD commented 9 years ago

A temporary but powerful solution to the lack of iterators, table.for_each lets a person iterate over the keys and values for a specified sol::table with each so long as they give it a function which takes a sol::object key, sol::object value.

Rapptz commented 9 years ago

I appreciate the addition but I'm not sure if it's actually worth adding.

I'll add it if you add tests.

ThePhD commented 9 years ago

@Rapptz All set!

Rapptz commented 9 years ago

I'm thinking of moving this from a member function to a free function.

sol::for_each(table, func);

But I guess iterators (which we've discussed extensively) would be a better solution which is hard-ish to do.

ThePhD commented 9 years ago

It's do-able if you used a std::shared_ptr to put the state of the iterator, because that allows the "shallow-copyable" iterator principle the std:: uses to work. The only semantics that don't work are saving state (e.g. auto it = table.begin(); auto saved = it; ++it; ++it;/* incrementing either will result in being 2 ahead on both, not 1, skipping a value */ ). I can't think of a way to do "saved position in iteration" because everything is tied to the current lua stack, and there's no way to successfully dupe the stack mid-iteration without destroying the iteration (and causing a segfault if you attempt to keep going after "fixing" the stack).