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

Custom module loaders not working? #1585

Open ethindp opened 4 months ago

ethindp commented 4 months ago

I'm uncertain if this is the place for questions, but I might be doing something wrong and this might not be a bug with Sol2 at all.

What's happening is that when I create a Lua state like so:

sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::package);
lua.clear_package_loaders();
lua.add_package_loader(load_module);

Modules that I know I've included aren't being loaded by require. My module function is like this:

int load_module(lua_State* L) {
  std::call_once(stdlib_loaded, [L]() {
    std::scoped_lock lock(modules_lock);
    modules["core"] = core::instantiate(L);
    modules["input"] = input::instantiate(L);
    modules["audio"] = audio::instantiate(L);
  });
  std::string name = sol::stack::get<std::string>(L, 1);
  modules_lock.lock_shared();
  if (modules.contains(name)) {
    sol::stack::push(L, modules[name]);
    return 1;
  }
  modules_lock.unlock_shared();
  sol::stack::push(L, sol::nil);
  sol::stack::push(L, std::format("Module {} does not exist", name));
  return 2;
}

I used to just push a string if the load failed, like the examples do, but I thought I'd try also pushing sol::nil but that still doesn't work. When a module isn't found, the string that I push isn't displayed in the error, just that module x could not be found or something like that. And in my test code, I'm require-ing a module that I know for a fact is available, but Lua still can't find it. Is this a bug or am I just messing up somehow? (For reference, the modules map is an std::unordered_map<std::string, sol::table>, protected by a std::shared_mutex and initialized via a std::once_flag. (The mutex probably isn't necessary but I'm intending to add a threading module so the modules map will need to be accessed potentially from multiple threads.)

ethindp commented 3 months ago

ping @ThePhD