bettola/common/src/lua_processor.cpp

46 lines
1.5 KiB
C++

#include "lua_processor.h"
#include <sol/forward.hpp>
#include <sol/object.hpp>
#include <sol/protected_function_result.hpp>
#include "vfs.h"
LuaProcessor::LuaProcessor(void) {
_lua.open_libraries(sol::lib::base, sol::lib::string, sol::lib::io, sol::lib::table);
/* Expose vfs_node struct members to Lua. */
_lua.new_usertype<vfs_node>("vfs_node",
"name", &vfs_node::name,
"type", &vfs_node::type,
"children", &vfs_node::children,
"content", &vfs_node::content); }
LuaProcessor::~LuaProcessor(void) {}
sol::object LuaProcessor::execute(const std::string& script, vfs_node* current_dir,
const std::vector<std::string>& args, bool is_remote) {
try {
/* Pass C++ objects/points into the Lua env. */
_lua["is_remote_session"] = is_remote;
_lua["current_dir"] = current_dir;
/* Create and populate the 'arg' table for the script. */
sol::table arg_table = _lua.create_table();
for(size_t i = 0; i < args.size(); ++i) {
arg_table[i+1] = args[i]; /* Lua arrays 1-indexed. */
}
_lua["arg"] = arg_table;
sol::protected_function_result result = _lua.safe_script(script);
if(result.valid()) {
return result;
} else {
sol::error err = result;
return sol::make_object(_lua, err.what());
}
} catch(const sol::error& e) {
/* Return the error message as a string in a sol::object. */
return sol::make_object(_lua, e.what());
}
}