ThePhD / sol2

Sol3 (sol2 v3.0) - a C++ <-> Lua API wrapper with advanced features and top notch performance - is here, and it's great! Documentation:
http://sol2.rtfd.io/
MIT License
4.12k stars 500 forks source link

`__newindex` is not calling if there is a metamethod with the same name #1424

Open mihacooper opened 1 year ago

mihacooper commented 1 year ago

Hello, I'm trying to migrate my project from solV2 to solV3 and found some problem with usage of metamethods __index/__newindex.

Here is simple usertype with defined both __index and __newindex

struct Sample {
    sol::object index(const sol::stack_object& key) {
        return sol::object();
    }
    void newIndex(const sol::stack_object& key, const sol::stack_object&) {
        std::cout << "newIndex called with key '" << key.as<std::string>() << "'" << std::endl;
    }
};

auto sampleType = lua.new_usertype<Sample>("sample");
sampleType[sol::meta_function::new_index] = &Sample::newIndex;
sampleType[sol::meta_function::index] = &Sample::index;

and after that I'm trying yo use it in lua:

local s = sample.new()

s.key = 2
s.__index = 2
s.key2 = 2

Here should be 3 calls of __newindex, but It will prints only 2 calls:

newIndex called with key 'key'
newIndex called with key 'key2'

So, the problem is that sol is considering existence of metamethod __index as existence of table key with name __index. This behaviour differ from solV2 and I'm trying to figure out is it feature or bug?)

Many thanks.