Files
dl_old/dl/script/dl_script_variable.h
T
2024-01-13 14:46:32 +08:00

142 lines
2.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* @file dl_script_variable.h
* @brief dl脚本变量
*
*
* @version 1.0
* @author lveyou
* @date 24-01-08
*
* @note 设计为可独立使用
*/
#pragma once
#include <variant>
#include "io/dl_log.h"
namespace dl::Script
{
class Variable;
using Function = std::function<int(std::vector<Variable>)>;
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<std::string>(_val);
}
operator Function() const
{
if (_type != Type::FUNCTION)
{
log_err("类型不是函数,当前为{}!", to_string(_type));
return {};
}
return std::get<Function>(_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<std::string>(_val);
case dl::Script::Variable::Type::FUNCTION:
//Function func = std::get<Function>(_val);
return "function_xx";
case dl::Script::Variable::Type::TABLE:
return "table_xx";
default:
break;
}
assert(0);
return "error";
}
private:
std::variant<int, std::string, Function> _val;
Type _type;
void _copy(const Variable& b)
{
_type = b._type;
_val = b._val;
}
};
}