/** * @file dl_script_variable.h * @brief dl脚本变量 * * * @version 1.0 * @author lveyou * @date 24-01-08 * * @note 设计为可独立使用 */ #pragma once #include "io/dl_log.h" namespace dl::Script { class Variable; using Function = std::function)>; class Variable { public: enum class Type { NIL, NUMBER, STRING, FUNCTION, TABLE }; std::string_view to_string(Type type) const { switch (type) { case Type::NIL: return "nil"; case Type::NUMBER: return "number"; case Type::STRING: return "string"; case Type::FUNCTION: return "function"; case Type::TABLE: return "table"; } return "error"; } Variable() : _type{ Type::NIL }, _func{ nullptr } {} ~Variable() {} Variable& operator=(const Variable& b) { _copy(b); return *this; } Variable(const Variable& b) { _copy(b); } Variable(std::string_view str) : _type{ Type::STRING }, _str{ str } {} Variable(Function func) : _type{ Type::FUNCTION }, _func{ func } {} operator std::string_view() const { if (_type != Type::STRING) { log_err("类型不是字符串,当前为{}!", to_string(_type)); return {}; } return _str; } operator Function() const { if (_type != Type::FUNCTION) { log_err("类型不是函数,当前为{}!", to_string(_type)); return {}; } return _func; } private: union { Function _func; std::string _str; }; Type _type; void _copy(const Variable& b) { _type = b._type; switch (_type) { case dl::Script::Variable::Type::NIL: break; case dl::Script::Variable::Type::NUMBER: break; case dl::Script::Variable::Type::STRING: _str = b._str; break; case dl::Script::Variable::Type::FUNCTION: _func = b._func; break; case dl::Script::Variable::Type::TABLE: break; default: break; } } }; }