2019-05-22 07:17:31 +08:00
|
|
|
#define SOL_ALL_SAFETIES_ON 1
|
2018-09-28 13:27:38 +08:00
|
|
|
#include <sol/sol.hpp>
|
2017-04-03 04:10:00 +08:00
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
|
2021-03-06 23:14:48 +08:00
|
|
|
void test_environment(std::string key,
|
|
|
|
const sol::environment& env, const sol::state_view& lua) {
|
2017-04-03 04:10:00 +08:00
|
|
|
sol::optional<int> maybe_env_a = env[key];
|
|
|
|
sol::optional<int> maybe_global_a = lua[key];
|
|
|
|
if (maybe_global_a) {
|
2021-03-06 23:14:48 +08:00
|
|
|
std::cout << "\t'" << key << "' is "
|
|
|
|
<< maybe_global_a.value()
|
|
|
|
<< " in the global environment" << std::endl;
|
2017-04-03 04:10:00 +08:00
|
|
|
}
|
|
|
|
else {
|
2021-03-06 23:14:48 +08:00
|
|
|
std::cout
|
|
|
|
<< "\t'" << key
|
|
|
|
<< "' does not exist in the global environment"
|
|
|
|
<< std::endl;
|
2017-04-03 04:10:00 +08:00
|
|
|
}
|
|
|
|
if (maybe_env_a) {
|
2021-03-06 23:14:48 +08:00
|
|
|
std::cout << "\t'" << key << "' is "
|
|
|
|
<< maybe_env_a.value()
|
|
|
|
<< " in target environment" << std::endl;
|
2017-04-03 04:10:00 +08:00
|
|
|
}
|
|
|
|
else {
|
2021-03-06 23:14:48 +08:00
|
|
|
std::cout << "\t'" << key
|
|
|
|
<< "' does not exist in target environment"
|
|
|
|
<< std::endl;
|
2017-04-03 04:10:00 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
int main(int, char**) {
|
2018-03-16 05:16:28 +08:00
|
|
|
std::cout << "=== environments ===" << std::endl;
|
2017-04-03 04:10:00 +08:00
|
|
|
|
|
|
|
sol::state lua;
|
|
|
|
// A global variable to see if we can "fallback" into it
|
|
|
|
lua["b"] = 2142;
|
|
|
|
|
|
|
|
// Create a new environment
|
|
|
|
sol::environment plain_env(lua, sol::create);
|
|
|
|
// Use it
|
|
|
|
lua.script("a = 24", plain_env);
|
|
|
|
std::cout << "-- target: plain_env" << std::endl;
|
|
|
|
test_environment("a", plain_env, lua);
|
|
|
|
test_environment("b", plain_env, lua);
|
|
|
|
std::cout << std::endl;
|
|
|
|
|
|
|
|
// Create an environment with a fallback
|
2021-03-06 23:14:48 +08:00
|
|
|
sol::environment env_with_fallback(
|
|
|
|
lua, sol::create, lua.globals());
|
2017-04-03 04:10:00 +08:00
|
|
|
// Use it
|
|
|
|
lua.script("a = 56", env_with_fallback);
|
2021-03-06 23:14:48 +08:00
|
|
|
std::cout << "-- target: env_with_fallback (fallback is "
|
|
|
|
"global table)"
|
|
|
|
<< std::endl;
|
2017-04-03 04:10:00 +08:00
|
|
|
test_environment("a", env_with_fallback, lua);
|
|
|
|
test_environment("b", env_with_fallback, lua);
|
|
|
|
std::cout << std::endl;
|
|
|
|
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|