#include "scripting.h" #include #include #include #include "../../files/engine_paths.h" #include "../../files/files.h" #include "../../util/timeutil.h" #include "../../world/Level.h" #include "../../voxels/Block.h" #include "api_lua.h" using namespace scripting; namespace scripting { extern lua_State* L; extern EnginePaths* paths; } lua_State* scripting::L = nullptr; Level* scripting::level = nullptr; const Content* scripting::content = nullptr; EnginePaths* scripting::paths = nullptr; void delete_global(lua_State* L, const char* name) { lua_pushnil(L); lua_setglobal(L, name); } bool rename_global(lua_State* L, const char* src, const char* dst) { lua_getglobal(L, src); if (lua_isnil(L, lua_gettop(L))) { lua_pop(L, lua_gettop(L)); return false; } lua_setglobal(L, dst); delete_global(L, src); return true; } void call_func(lua_State* L, int argc, const std::string& name) { if (lua_pcall(L, argc, LUA_MULTRET, 0)) { std::cerr << "Lua error in " << name << ": "; std::cerr << lua_tostring(L,-1) << std::endl; } } void scripting::initialize(EnginePaths* paths) { scripting::paths = paths; L = luaL_newstate(); if (L == nullptr) { throw std::runtime_error("could not to initialize Lua"); } luaopen_base(L); luaopen_math(L); std::cout << LUA_VERSION << std::endl; # ifdef LUAJIT_VERSION luaopen_jit(L); std::cout << LUAJIT_VERSION << std::endl; # endif // LUAJIT_VERSION apilua::create_funcs(L); } void scripting::on_world_load(Level* level) { scripting::level = level; scripting::content = level->content; fs::path file = paths->getResources()/fs::path("scripts/world.lua"); std::string src = files::read_string(file); luaL_loadbuffer(L, src.c_str(), src.length(), file.string().c_str()); call_func(L, 0, "