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.06k stars 492 forks source link

for iterator lua tab in c++ leadto Segmentation fault #1536

Open liulover5 opened 9 months ago

liulover5 commented 9 months ago

Use for iterator lua tab in c++ leadto Segmentation fault, But other two style for run ok (note the for iterator)

SOL: 3.3.0 LUA:5.2.4 std c++: gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~18.04)

code:

        sol::table tab = lua.create_table_with("value", 24);  // tab = { value = 24 }
        tab[0] = false;
        tab["key"] = "key";

        //for (auto it = tab.begin(); it != tab.end(); it++);  // std::cout << it->first << " " << it->second << std::endl;
        for (auto it = tab.begin(); it != tab.end(); it++); // Segmentation fault
        for (auto[key, val] : tab);  //  OK
        for (auto it : tab); // OK

log:

I think mistake code maybe here in sol.h:

basic_table_iterator& operator++() {
                if (idx == -1)
                    return *this;

                if (lua_next(ref.lua_state(), tableidx) == 0) {
                    idx = -1;
                    keyidx = -1;
                    return *this;
                }
                ++idx;
                kvp.first = object(ref.lua_state(), -2);
                kvp.second = object(ref.lua_state(), -1);
                lua_pop(ref.lua_state(), 1);
                // leave key on the stack
                keyidx = lua_gettop(ref.lua_state());
                return *this;
            }

need help!

nimble0 commented 8 months ago

Use prefix increment (++it), mentioned here: https://sol2.readthedocs.io/en/latest/api/table.html#table-iterators