A simple scripting language in C++
Ferenc Szontágh
2025-04-19 3c645799476e526b04e13f648cd30643c1f39112
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// TypeofModule.hpp
#ifndef MODULES_TYPEOFMODULE_HPP
#define MODULES_TYPEOFMODULE_HPP
 
#include <string>
#include <vector>
#include "BaseModule.hpp"
#include "ModuleManager.hpp"
#include "Symbols/Value.hpp"
#include "Symbols/VariableTypes.hpp"
 
namespace Modules {
 
/**
 * @brief Module providing a typeof() function.
 * Usage:
 *   typeof($var)            -> returns string name of type ("int", "string", etc.)
 *   typeof($var, "int")   -> returns bool indicating if type matches
 */
class TypeofModule : public BaseModule {
  public:
    void registerModule() override {
        auto &mgr = ModuleManager::instance();
        mgr.registerFunction("typeof", [](const std::vector<Symbols::Value> &args) {
            using namespace Symbols;
            if (args.size() == 1) {
                auto t = args[0].getType();
                return Value(Variables::TypeToString(t));
            } else if (args.size() == 2) {
                auto t = args[0].getType();
                std::string name = Variables::TypeToString(t);
                if (args[1].getType() != Variables::Type::STRING) {
                    throw std::runtime_error("Second argument to typeof must be string");
                }
                bool match = (name == args[1].get<std::string>());
                return Value(match);
            }
            throw std::runtime_error("typeof expects 1 or 2 arguments");
        });
    }
};
 
} // namespace Modules
 
#endif // MODULES_TYPEOFMODULE_HPP