| 98 | } |
| 99 | |
| 100 | static int insertion_function(lua_State* L) { |
| 101 | sol::stack_object source(L, 1); |
| 102 | sol::stack_object key(L, 2); |
| 103 | sol::stack_object value(L, 3); |
| 104 | if (!source.is<thing>()) { |
| 105 | return luaL_error(L, |
| 106 | "given an incorrect object for this " |
| 107 | "call"); |
| 108 | } |
| 109 | // write to member variables, etc. etc... |
| 110 | sol::optional<sol::string_view> maybe_svkey |
| 111 | = key.as<sol::optional<sol::string_view>>(); |
| 112 | if (maybe_svkey) { |
| 113 | { |
| 114 | // variables are different than funtions |
| 115 | // when someone does `obj.a`, they |
| 116 | // expect this __index call (this lookup |
| 117 | // function) to return to them the value |
| 118 | // itself they're seeing so we call out |
| 119 | // lua_CFunction that we serialized |
| 120 | // earlier |
| 121 | auto it |
| 122 | = thing_variable_associations.find( |
| 123 | *maybe_svkey); |
| 124 | if (it |
| 125 | != thing_variable_associations |
| 126 | .cend()) { |
| 127 | // note that calls generated by |
| 128 | // sol2 for member variables expect |
| 129 | // the stack ordering to be 2(, 3, |
| 130 | // ..., n) -- value(s) 1 -- source |
| 131 | // so we remove the key value |
| 132 | sol::stack::remove(L, 2, 1); |
| 133 | lua_CFunction cf |
| 134 | = it->second |
| 135 | .as<lua_CFunction>(); |
| 136 | return cf(L); |
| 137 | } |
| 138 | else { |
| 139 | // write to member variable, maybe |
| 140 | // override function if your class |
| 141 | // allows for it? |
| 142 | (void)value; |
| 143 | } |
| 144 | } |
| 145 | // exercise for reader: |
| 146 | // how do you override functions on the |
| 147 | // metatable with proper syntax, but error |
| 148 | // when the type is an "instance" object? |
| 149 | } |
| 150 | return 0; |
| 151 | } |
| 152 | }; |
| 153 | |
| 154 | lua.new_usertype<thing>("thing"); |