Over the past couple of commits, the build process now automates the dependenices you'd normally compile from source. This commit is focused on laying the foundation for scriptable in-game commands using Lua. - sol2 and lua5.4 are the new project dependencies. - Created a new 'LuaProcessor' class to manage a Lua state and eecute scripts. - The 'CommandProcessor' now contains a 'LuaProcessor' instance. - Replaced the hardcoded c++ 'ls' command with a system that executes a '/bin/ls.lua' script from the Virtual File System. - Implemented C++ -> Lua bindings for the 'vfs_node' struct, allowing Lua scripts to inspect the VFS and perform actions (i.e, list files).
66 lines
2.0 KiB
C++
66 lines
2.0 KiB
C++
#include "command_processor.h"
|
|
#include "vfs.h"
|
|
#include "lua_processor.h"
|
|
|
|
CommandProcessor::CommandProcessor(vfs_node* starting_dir) {
|
|
_current_dir = starting_dir;
|
|
_lua = new LuaProcessor();
|
|
}
|
|
|
|
CommandProcessor::~CommandProcessor(void) {
|
|
delete _lua;
|
|
}
|
|
|
|
vfs_node* CommandProcessor::get_current_dir(void) {
|
|
return _current_dir;
|
|
}
|
|
|
|
std::string CommandProcessor::process_command(const std::string& command) {
|
|
/* Trim trailing whitespace. */
|
|
std::string cmd = command;
|
|
size_t end = cmd.find_last_not_of(" \t\n\r");
|
|
cmd = (end == std::string::npos) ? "" : cmd.substr(0, end+1);
|
|
|
|
if(command.rfind("cd ", 0) == 0) {
|
|
std::string target_dir_name = command.substr(3);
|
|
if(target_dir_name == "..") {
|
|
if(_current_dir->parent) {
|
|
_current_dir = _current_dir->parent;
|
|
}
|
|
} else if(_current_dir->children.count(target_dir_name)) {
|
|
vfs_node* target_node = _current_dir->children[target_dir_name];
|
|
if(target_node->type == DIR_NODE) {
|
|
_current_dir = target_node;
|
|
} else {
|
|
return "cd: not a directory\n";
|
|
}
|
|
} else {
|
|
return "cd: no such file or directory\n";
|
|
}
|
|
return get_full_path(_current_dir);
|
|
} else if(cmd == "ls") {
|
|
/* Find the root of the VFS to look for the /bin directory. */
|
|
vfs_node* root = _current_dir;
|
|
while(root->parent != nullptr) {
|
|
root = root->parent;
|
|
}
|
|
|
|
fprintf(stderr, "DEBUG: VFS root found, name: '%s'\n", root->name.c_str());
|
|
|
|
/* Find and execute the ls.lua script. */
|
|
if(root->children.count("bin")) {
|
|
fprintf(stderr, "DEBUG: Found '/bin' directory.\n");
|
|
vfs_node* bin_dir = root->children["bin"];
|
|
if(bin_dir->children.count("ls.lua")) {
|
|
fprintf(stderr, "DEBUG: Found '/bin/ls.lua'. Executing.\n");
|
|
vfs_node* ls_script_node = bin_dir->children["ls.lua"];
|
|
return _lua->execute(ls_script_node->content, _current_dir);
|
|
}
|
|
}
|
|
fprintf(stderr, "DEBUG: 'ls' command failed to find '/bin/ls.lua'.\n");
|
|
return "ls: command not found\n";
|
|
}
|
|
|
|
return "Unknown command: " + command + "\n";
|
|
}
|