Skip to content

Commit

Permalink
engine(lua): Auto-require cloe in cloe-engine shell
Browse files Browse the repository at this point in the history
This could also easily be added for normal run, but it
seems like this is a good compromise between clarity and easy-of-use.
(The auto-require feature will feel like magic to users.)
  • Loading branch information
cassava committed Oct 23, 2023
1 parent f24eb10 commit 914d3f3
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
30 changes: 30 additions & 0 deletions engine/src/lua_setup.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,33 @@ void register_cloe_engine_fs(sol::state_view& lua) {
luat_cloe_engine_fs(lua) = tbl;
}

/**
* Add cloe lazy-loader into Lua global namespace.
*
* You can just use `cloe`, and it will auto-require the cloe module.
* If you don't use it, then it won't be loaded.
*/
void register_cloe(sol::state_view& lua) {
// This takes advantage of the `__index` function for metatables, which is called
// when a key can't be found in the original table, here an empty table
// assigned to cloe. It then loads the cloe module, and returns the key
// requested. The next access will no longer trigger this method, because we
// swapped tables.
//
// Effectively, this lazy-loads the cloe library. This allows us to not
// load it and all the other modules it pulls in, which allows us to for
// example, configure those libraries before cloe does.
auto result = lua.safe_script(R"==(
cloe = setmetatable({}, {
__index = function(_, k)
_G["cloe"] = require("cloe")
return _G["cloe"][k]
end
})
)==");
assert(result.valid());
}

} // anonymous namespace

sol::state new_lua(const LuaOptions& opt, Stack& stack) {
Expand All @@ -284,6 +311,9 @@ sol::state new_lua(const LuaOptions& opt, Stack& stack) {
register_cloe_engine(lua, stack);
register_cloe_engine_types(lua);
register_cloe_engine_fs(lua);
if (opt.auto_require_cloe) {
register_cloe(lua);
}
return lua;
}

Expand Down
1 change: 1 addition & 0 deletions engine/src/lua_setup.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ struct LuaOptions {

std::vector<std::string> lua_paths;
bool no_system_lua = false;
bool auto_require_cloe = false;
};

/**
Expand Down
4 changes: 3 additions & 1 deletion engine/src/main_shell.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,9 @@ int shell(const ShellOptions& opt, const std::vector<std::string>& filepaths) {

cloe::StackOptions stack_opt = opt.stack_options;
cloe::Stack stack = cloe::new_stack(stack_opt);
sol::state lua = cloe::new_lua(opt.lua_options, stack);
auto lopt = opt.lua_options;
lopt.auto_require_cloe = true;
sol::state lua = cloe::new_lua(lopt, stack);

// Collect input files and strings to execute
std::vector<std::string> actions{};
Expand Down

0 comments on commit 914d3f3

Please sign in to comment.