sol2/examples/source/tutorials/variables_demo.cpp

80 lines
2.0 KiB
C++
Raw Normal View History

#define SOL_ALL_SAFETIES_ON 1
2019-07-04 23:16:03 +08:00
#include <sol/sol.hpp>
2018-11-10 06:36:27 +08:00
#include <tuple>
#include <utility> // for std::pair
int main() {
sol::state lua;
/*
lua.script_file("variables.lua");
*/
lua.script(R"(
config = {
fullscreen = false,
resolution = { x = 1024, y = 768 }
}
)");
// the type "sol::state" behaves
2018-11-10 06:36:27 +08:00
// exactly like a table!
bool isfullscreen
= lua["config"]
["fullscreen"]; // can get nested variables
2018-11-10 06:36:27 +08:00
sol::table config = lua["config"];
sol_c_assert(!isfullscreen);
2018-11-10 06:36:27 +08:00
// can also get it using the "get" member function
// auto replaces the unqualified type name
auto resolution = config.get<sol::table>("resolution");
// table and state can have multiple things pulled out of it
// too
std::tuple<int, int> xyresolutiontuple
= resolution.get<int, int>("x", "y");
sol_c_assert(std::get<0>(xyresolutiontuple) == 1024);
sol_c_assert(std::get<1>(xyresolutiontuple) == 768);
2018-11-10 06:36:27 +08:00
// test variable
auto bark = lua["config"]["bark"];
if (bark.valid()) {
// branch not taken: config and/or bark are not
// variables
2018-11-10 06:36:27 +08:00
}
else {
// Branch taken: config and bark are existing variables
}
// can also use optional
sol::optional<int> not_an_integer
= lua["config"]["fullscreen"];
2018-11-10 06:36:27 +08:00
if (not_an_integer) {
// Branch not taken: value is not an integer
}
sol::optional<bool> is_a_boolean
= lua["config"]["fullscreen"];
2018-11-10 06:36:27 +08:00
if (is_a_boolean) {
// Branch taken: the value is a boolean
}
sol::optional<double> does_not_exist
= lua["not_a_variable"];
2018-11-10 06:36:27 +08:00
if (does_not_exist) {
// Branch not taken: that variable is not present
}
// this will result in a value of '24'
// (it tries to get a number, and fullscreen is
// not a number
int is_defaulted = lua["config"]["fullscreen"].get_or(24);
sol_c_assert(is_defaulted == 24);
2018-11-10 06:36:27 +08:00
// This will result in the value of the config, which is
// 'false'
2018-11-10 06:36:27 +08:00
bool is_not_defaulted = lua["config"]["fullscreen"];
sol_c_assert(!is_not_defaulted);
2018-11-10 06:36:27 +08:00
return 0;
}