Basic operator[] support for tables

This commit is contained in:
Rapptz 2013-12-12 18:12:07 -05:00
parent d44a215216
commit 5eeaedec2f
2 changed files with 32 additions and 2 deletions

View File

@ -150,6 +150,11 @@ public:
return *this; return *this;
} }
template<typename T>
auto operator[](T&& key) -> decltype(global[std::forward<T>(key)]) {
return global[std::forward<T>(key)];
}
template<typename T> template<typename T>
table create_table(T&& key, int narr = 0, int nrec = 0) { table create_table(T&& key, int narr = 0, int nrec = 0) {
lua_createtable(L.get(), narr, nrec); lua_createtable(L.get(), narr, nrec);

View File

@ -38,8 +38,10 @@ namespace detail {
T* get_ptr(T* val) { T* get_ptr(T* val) {
return val; return val;
} }
} } // detail
class table : virtual public reference { class table : virtual public reference {
template<typename T> struct proxy;
public: public:
table() noexcept : reference() {} table() noexcept : reference() {}
table(lua_State* L, int index = -1) : reference(L, index) { table(lua_State* L, int index = -1) : reference(L, index) {
@ -79,12 +81,16 @@ public:
std::forward<T>(key), std::forward<TFx>(fx), std::forward<TObj>(obj)); std::forward<T>(key), std::forward<TFx>(fx), std::forward<TObj>(obj));
} }
template<typename T>
proxy<T> operator[](T&& key) {
return proxy<T>(*this, std::forward<T>(key));
}
size_t size() const { size_t size() const {
push(); push();
return lua_rawlen(state(), -1); return lua_rawlen(state(), -1);
} }
private: private:
template<typename T, typename TFx> template<typename T, typename TFx>
table& set_isfunction_fx(std::true_type, T&& key, TFx&& fx) { table& set_isfunction_fx(std::true_type, T&& key, TFx&& fx) {
return set_fx(std::false_type(), std::forward<T>(key), std::forward<TFx>(fx)); return set_fx(std::false_type(), std::forward<T>(key), std::forward<TFx>(fx));
@ -206,6 +212,25 @@ private:
lua_pop(state(), 1); lua_pop(state(), 1);
return *this; return *this;
} }
template<typename T>
struct proxy {
private:
table& t;
T& key;
public:
proxy(table& t, T& key): t(t), key(key) {}
template<typename U>
void operator=(U&& other) {
t.set(key, std::forward<U>(other));
}
template<typename U>
operator U() const {
return t.get<U>(key);
}
};
}; };
} // sol } // sol