wrenpp/examples/greet/main.cpp
King_DuckZ 65189a5575 Move files around
Sample main.cpp is now into examples/greet
2020-05-02 22:55:10 +02:00

95 lines
2.5 KiB
C++

/* Copyright 2020, Michele Santullo
* 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 <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)));
}
class MyConfig : public wren::DefConfiguration {
public:
wren::foreign_method_t foreign_method_fn (
wren::VM* vm,
const char* module_ptr,
const char* class_name_ptr,
bool is_static,
const char* signature_ptr
) {
//std::cout << "VM " << vm << " requested foreign method " << class_name << "::" << signature << " in module " << module << "\n";
std::string_view module(module_ptr);
std::string_view class_name(class_name_ptr);
std::string_view signature(signature_ptr);
if ("User" == class_name and "main" == module and "get_env(_)" == signature)
return &user_get_env;
return nullptr;
}
};
} //unnamed namespace
int main() {
//typedef wren::ModuleAndName MN;
MyConfig config;
wren::VM vm(&config, nullptr);
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;
}