#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 "../../items/ItemDef.h" #include "../../logic/BlocksController.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; BlocksController* scripting::blocks = nullptr; inline int lua_pushivec3(lua_State* L, int x, int y, int z) { lua_pushinteger(L, x); lua_pushinteger(L, y); lua_pushinteger(L, z); return 3; } 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; } int 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; return 0; } return 1; } void scripting::initialize(EnginePaths* paths) { scripting::paths = paths; L = luaL_newstate(); if (L == nullptr) { throw std::runtime_error("could not to initialize Lua"); } // Allowed standard libraries luaopen_base(L); luaopen_math(L); luaopen_string(L); luaopen_table(L); // io-manipulations will be implemented via api functions 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, BlocksController* blocks) { scripting::level = level; scripting::content = level->content; scripting::blocks = blocks; 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, "