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

add_package_loader without lua_CFunction #1601

Open Gerark opened 2 months ago

Gerark commented 2 months ago

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?