sol2 icon indicating copy to clipboard operation
sol2 copied to clipboard

add_package_loader without lua_CFunction

Open Gerark opened this issue 1 year ago • 1 comments

I've seen the code example of how to use the add_package_loader but I'm not sure if I can use it by passing a simpler lambda.

This is what I'm trying to do:

luaState.add_package_loader([this](std::string_view moduleToLoad) {
    if (moduleToLoad == "bindings.input") {
        return sol::make_object(luaState, luaState.create_table_with(
           "doSomething", [](){}
        ));
    }
    return sol::make_object(luaState, "This is not the module you're looking for!");
});
local input = require "bindings.input"
input.doSomething()

The lambda is called successfully with the right value in the moduleToLoad. But for some reason I still get this error:

An unexpected error has occurred: sol: runtime error: ..scripts\core\input.lua:2: module 'bindings.input' not found:
        no field package.preload['bindings.input']

Am I supposed to only pass lua_CFunction to the add_package_loader or is it just my approach missing something?

Gerark avatar Apr 27 '24 22:04 Gerark

For reference, this worked:

    _solState->add_package_loader([this](const std::string &module) {
        if (module.starts_with("bindings.")) {
            return _solState->load(fmt::format("return _createBindingTable('{}')", module), module).get<sol::object>();
        } else {
            // Note that "\n\t" is needed here so that the error message is properly formatted, see `searchpath`
            // function in lua sources.
            return sol::make_object(*_solState, fmt::format("\n\tno bindings module '{}'", module));
        }
    });

See https://github.com/OpenEnroth/OpenEnroth/pull/1745/commits/ad624dd1b4e92f1c034c8b5a71cc0177a508bed1.

Can close this issue.

captainurist avatar Jul 28 '24 19:07 captainurist