Phasor 2.2.0
Stack VM based Programming Language
Loading...
Searching...
No Matches
typeconv.cpp
Go to the documentation of this file.
1#include "StdLib.hpp"
2
3namespace Phasor
4{
5
6Value StdLib::registerTypeConvFunctions(const std::vector<Value> &args, VM *vm)
7{
8 checkArgCount(args, 0, "include_stdtype");
13 return true;
14}
15
16Value StdLib::to_int(const std::vector<Value> &args, VM *)
17{
18 checkArgCount(args, 1, "to_int");
19 if (args[0].isInt())
20 return args[0];
21 if (args[0].isFloat())
22 return Value(static_cast<int64_t>(args[0].asFloat()));
23 if (args[0].isString())
24 {
25 try
26 {
27 return static_cast<int64_t>(std::stoll(args[0].asString()));
28 }
29 catch (...)
30 {
31 return 0;
32 }
33 }
34 if (args[0].isBool())
35 return args[0].asBool() ? 1 : 0;
36 return 0;
37}
38
39Value StdLib::to_float(const std::vector<Value> &args, VM *)
40{
41 checkArgCount(args, 1, "to_float");
42 return args[0].asFloat();
43}
44
45Value StdLib::to_string(const std::vector<Value> &args, VM *)
46{
47 checkArgCount(args, 1, "to_string");
48 return args[0].toString();
49}
50
51Value StdLib::to_bool(const std::vector<Value> &args, VM *)
52{
53 checkArgCount(args, 1, "to_bool");
54 if (args[0].isBool())
55 return args[0];
56 if (args[0].isInt())
57 return args[0].asInt() != 0;
58 if (args[0].isString())
59 return !args[0].asString().empty();
60 return false;
61}
62
63} // namespace Phasor
static void checkArgCount(const std::vector< Value > &args, size_t minimumArguments, const std::string &name, bool allowMoreArguments=false)
Definition StdLib.cpp:50
static Value to_int(const std::vector< Value > &args, VM *vm)
Convert to integer.
Definition typeconv.cpp:16
static Value registerTypeConvFunctions(const std::vector< Value > &args, VM *vm)
Definition typeconv.cpp:6
static Value to_float(const std::vector< Value > &args, VM *vm)
Convert to float.
Definition typeconv.cpp:39
static Value to_bool(const std::vector< Value > &args, VM *vm)
Convert to boolean.
Definition typeconv.cpp:51
static Value to_string(const std::vector< Value > &args, VM *vm)
Convert to string.
Definition typeconv.cpp:45
Virtual Machine.
Definition VM.hpp:18
void registerNativeFunction(const std::string &name, NativeFunction fn)
Register a native function.
Definition VM.cpp:869
A value in the Phasor VM.
Definition Value.hpp:33
The Phasor Programming Language and Runtime.
Definition AST.hpp:8