wrenpp/examples/greet/main.cpp

79 lines
2 KiB
C++
Raw Normal View History

2022-04-28 20:56:11 +00:00
/* Copyright 2020-2022, Michele Santullo
2020-04-30 21:33:54 +00:00
* This file is part of wrenpp.
*
* Wrenpp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Wrenpp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with wrenpp. If not, see <http://www.gnu.org/licenses/>.
*/
#include "wrenpp/vm_fun.hpp"
#include "wrenpp/def_configuration.hpp"
#include "wrenpp/callback_manager.hpp"
#include <chrono>
#include <thread>
#include <unistd.h>
#if defined(__GNU_LIBRARY__) && ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 17) || __GLIBC__ > 2)
# define HasSecureGetenv
#endif
namespace {
const constexpr char g_script[] = ""
R"script(class User {
construct new(nm) {
_name = nm
}
foreign static get_env(name)
greet() {
System.print("Hello %(_name), from wren script!")
}
}
var the_user = User.new(User.get_env("USER"))
)script";
const char* raw_fetch_env (const char* name) noexcept {
if (not name)
return nullptr;
#if defined(HasSecureGetenv)
const char* const val_ptr = secure_getenv(name);
#else
const char* const val_ptr = getenv(name);
#endif
return val_ptr;
}
void user_get_env (wren::VM& vm) {
set(vm, 0, raw_fetch_env(wren::get<const char*>(vm, 1)));
}
} //unnamed namespace
int main() {
//typedef wren::ModuleAndName MN;
wren::DefConfiguration config;
wren::VM vm(&config, nullptr);
vm.callback_manager().add_callback(true, "main", "User", "get_env(_)", &user_get_env);
vm.interpret("main", g_script);
wren::call<void>(vm, {"main", "the_user"}, "greet");
std::cout << "Quitting in 1 sec" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
return 0;
}