/** * @file dl_script_variable.h * @brief dl脚本变量 * * * @version 1.0 * @author lveyou * @date 24-01-08 * * @note 设计为可独立使用 */ #pragma once #include #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, VAR_LOCAL }; 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"; } assert(0); return "error"; } Variable() : _type{ Type::NIL }, _val{ 0 } {} ~Variable() {} Variable& operator=(const Variable& b) { _copy(b); return *this; } Variable(const Variable& b) { _copy(b); } Variable(const std::string& str) : _type{ Type::STRING }, _val{ str } {} Variable(std::string_view str) : _type{ Type::STRING }, _val{ std::string{str} } {} Variable(Function func) : _type{ Type::FUNCTION }, _val{ func } {} Variable(int tag, std::string_view str) : _type{ Type::VAR_LOCAL }, _val{ std::string{str} } {} operator std::string_view() const { if (_type != Type::STRING) { log_err("类型不是字符串,当前为{}!", to_string(_type)); return {}; } return std::get(_val); } operator Function() const { if (_type != Type::FUNCTION) { log_err("类型不是函数,当前为{}!", to_string(_type)); return {}; } return std::get(_val); } Type GetType() const { return _type; } std::string GetString() const { switch (_type) { case dl::Script::Variable::Type::NIL: return "nil"; case dl::Script::Variable::Type::NUMBER: return "12345"; case dl::Script::Variable::Type::STRING: case dl::Script::Variable::Type::VAR_LOCAL: return std::get(_val); case dl::Script::Variable::Type::FUNCTION: //Function func = std::get(_val); return "function_xx"; case dl::Script::Variable::Type::TABLE: return "table_xx"; default: break; } assert(0); return "error"; } private: std::variant _val; Type _type; void _copy(const Variable& b) { _type = b._type; _val = b._val; } }; }