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