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 493 forks source link

is it possible to loop over a table and extract all variables dec;ared? #1488

Closed reworks-org closed 1 year ago

reworks-org commented 1 year ago

I.e.

local example = {}

example["x"] = 1;
example["y"] = 2;

function example:construct(self)
end

function example:update(self)
end

function example:destruct(self)
end

return example

then in C++, iterate over table and store a sol::object to each variable so we can modify from C++ side. So I can store "x" and "y" in a hash_map locally, or just loop over table since they already stored there. Basically I want to loop over the variables in the table and be able to modify them from a gui. I dont mind pulling out function names either, I assume there is a way to differentiate them.

Rochet2 commented 1 year ago

Here is one example. Works, but maybe not the best one.

#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

int main() {
    sol::state lua;
    lua.open_libraries();

    sol::table example = lua.script(R"(
        local example = {}

        example["x"] = 1;
        example["y"] = 2;

        function example:construct(self)
        end

        function example:update(self)
        end

        function example:destruct(self)
        end

        return example
    )");

    for (auto& it : example) {
        lua["print"](it.first, it.second);
        if (!it.second.is<int>())
            continue;
        example[it.first] = it.second.as<int>() + 1;
    }

    for (auto& it : example) {
        lua["print"](it.first, it.second);
    }
    return 0;
}

Insatead of this

        if (!it.second.is<int>())
            continue;

You can also do this

        if (it.second.get_type() == sol::type::function)
            continue;
reworks-org commented 1 year ago

this was what i needed. thanks.