code:
/*
Minetest
Copyright (C) 2017 Dumbeldor, Vincent Glize <vincent.glize@live.fr>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#ifndef MINETEST_L_LOCALPLAYER_H
#define MINETEST_L_LOCALPLAYER_H

#include "l_base.h"

class LocalPlayer;

class LuaLocalPlayer : public ModApiBase
{
private:
	static const char className[];
	static const luaL_Reg methods[];

	// garbage collector
	static int gc_object(lua_State *L);

	static int l_get_velocity(lua_State *L);

	static int l_get_hp(lua_State *L);

	static int l_get_name(lua_State *L);

	static int l_is_attached(lua_State *L);
	static int l_is_touching_ground(lua_State *L);
	static int l_is_in_liquid(lua_State *L);
	static int l_is_in_liquid_stable(lua_State *L);
	static int l_get_liquid_viscosity(lua_State *L);
	static int l_is_climbing(lua_State *L);
	static int l_swimming_vertical(lua_State *L);

	static int l_get_physics_override(lua_State *L);

	static int l_get_override_pos(lua_State *L);

	static int l_get_last_pos(lua_State *L);
	static int l_get_last_velocity(lua_State *L);
	static int l_get_last_look_vertical(lua_State *L);
	static int l_get_last_look_horizontal(lua_State *L);
	static int l_get_key_pressed(lua_State *L);

	static int l_get_breath(lua_State *L);

	static int l_get_pos(lua_State *L);

	static int l_get_movement_acceleration(lua_State *L);

	static int l_get_movement_speed(lua_State *L);

	static int l_get_movement(lua_State *L);

	LocalPlayer *m_localplayer;

public:
	LuaLocalPlayer(LocalPlayer *m);
	~LuaLocalPlayer() {}

	static void create(lua_State *L, LocalPlayer *m);

	static LuaLocalPlayer *checkobject(lua_State *L, int narg);
	static LocalPlayer *getobject(LuaLocalPlayer *ref);
	static LocalPlayer *getobject(lua_State *L, int narg);

	static void Register(lua_State *L);
};

#endif // MINETEST_L_LOCALPLAYER_H


code:
/*
Minetest
Copyright (C) 2013 sapier

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "lua_api/l_mainmenu.h"
#include "lua_api/l_internal.h"
#include "common/c_content.h"
#include "cpp_api/s_async.h"
#include "guiEngine.h"
#include "guiMainMenu.h"
#include "guiKeyChangeMenu.h"
#include "guiFileSelectMenu.h"
#include "subgame.h"
#include "version.h"
#include "porting.h"
#include "filesys.h"
#include "convert_json.h"
#include "serverlist.h"
#include "mapgen.h"
#include "settings.h"
#include "EDriverTypes.h"

#include <IFileArchive.h>
#include <IFileSystem.h>

/******************************************************************************/
std::string ModApiMainMenu::getTextData(lua_State *L, std::string name)
{
	lua_getglobal(L, "gamedata");

	lua_getfield(L, -1, name.c_str());

	if(lua_isnil(L, -1))
		return "";

	return luaL_checkstring(L, -1);
}

/******************************************************************************/
int ModApiMainMenu::getIntegerData(lua_State *L, std::string name,bool& valid)
{
	lua_getglobal(L, "gamedata");

	lua_getfield(L, -1, name.c_str());

	if(lua_isnil(L, -1)) {
		valid = false;
		return -1;
		}

	valid = true;
	return luaL_checkinteger(L, -1);
}

/******************************************************************************/
int ModApiMainMenu::getBoolData(lua_State *L, std::string name,bool& valid)
{
	lua_getglobal(L, "gamedata");

	lua_getfield(L, -1, name.c_str());

	if(lua_isnil(L, -1)) {
		valid = false;
		return false;
		}

	valid = true;
	return lua_toboolean(L, -1);
}

/******************************************************************************/
int ModApiMainMenu::l_update_formspec(lua_State *L)
{
	GUIEngine* engine = getGuiEngine(L);
	sanity_check(engine != NULL);

	if (engine->m_startgame)
		return 0;

	//read formspec
	std::string formspec(luaL_checkstring(L, 1));

	if (engine->m_formspecgui != 0) {
		engine->m_formspecgui->setForm(formspec);
	}

	return 0;
}

/******************************************************************************/
int ModApiMainMenu::l_start(lua_State *L)
{
	GUIEngine* engine = getGuiEngine(L);
	sanity_check(engine != NULL);

	//update c++ gamedata from lua table

	bool valid = false;

	MainMenuData *data = engine->m_data;

	data->selected_world = getIntegerData(L, "selected_world",valid) -1;
	data->simple_singleplayer_mode = getBoolData(L,"singleplayer",valid);
	data->do_reconnect = getBoolData(L, "do_reconnect", valid);
	if (!data->do_reconnect) {
		data->name     = getTextData(L,"playername");
		data->password = getTextData(L,"password");
		data->address  = getTextData(L,"address");
		data->port     = getTextData(L,"port");
	}
	data->serverdescription = getTextData(L,"serverdescription");
	data->servername        = getTextData(L,"servername");

	//close menu next time
	engine->m_startgame = true;
	return 0;
}

/******************************************************************************/
int ModApiMainMenu::l_close(lua_State *L)
{
	GUIEngine* engine = getGuiEngine(L);
	sanity_check(engine != NULL);

	engine->m_kill = true;
	return 0;
}

/******************************************************************************/
int ModApiMainMenu::l_set_background(lua_State *L)
{
	GUIEngine* engine = getGuiEngine(L);
	sanity_check(engine != NULL);

	std::string backgroundlevel(luaL_checkstring(L, 1));
	std::string texturename(luaL_checkstring(L, 2));

	bool tile_image = false;
	bool retval     = false;
	unsigned int minsize = 16;

	if (!lua_isnone(L, 3)) {
		tile_image = lua_toboolean(L, 3);
	}

	if (!lua_isnone(L, 4)) {
		minsize = lua_tonumber(L, 4);
	}

	if (backgroundlevel == "background") {
		retval |= engine->setTexture(TEX_LAYER_BACKGROUND, texturename,
				tile_image, minsize);
	}

	if (backgroundlevel == "overlay") {
		retval |= engine->setTexture(TEX_LAYER_OVERLAY, texturename,
				tile_image, minsize);
	}

	if (backgroundlevel == "header") {
		retval |= engine->setTexture(TEX_LAYER_HEADER,  texturename,
				tile_image, minsize);
	}

	if (backgroundlevel == "footer") {
		retval |= engine->setTexture(TEX_LAYER_FOOTER, texturename,
				tile_image, minsize);
	}

	lua_pushboolean(L,retval);
	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_set_clouds(lua_State *L)
{
	GUIEngine* engine = getGuiEngine(L);
	sanity_check(engine != NULL);

	bool value = lua_toboolean(L,1);

	engine->m_clouds_enabled = value;

	return 0;
}

/******************************************************************************/
int ModApiMainMenu::l_get_textlist_index(lua_State *L)
{
	// get_table_index accepts both tables and textlists
	return l_get_table_index(L);
}

/******************************************************************************/
int ModApiMainMenu::l_get_table_index(lua_State *L)
{
	GUIEngine* engine = getGuiEngine(L);
	sanity_check(engine != NULL);

	std::string tablename(luaL_checkstring(L, 1));
	GUITable *table = engine->m_menu->getTable(tablename);
	s32 selection = table ? table->getSelected() : 0;

	if (selection >= 1)
		lua_pushinteger(L, selection);
	else
		lua_pushnil(L);
	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_get_worlds(lua_State *L)
{
	std::vector<WorldSpec> worlds = getAvailableWorlds();

	lua_newtable(L);
	int top = lua_gettop(L);
	unsigned int index = 1;

	for (unsigned int i = 0; i < worlds.size(); i++)
	{
		lua_pushnumber(L,index);

		lua_newtable(L);
		int top_lvl2 = lua_gettop(L);

		lua_pushstring(L,"path");
		lua_pushstring(L,worlds[i].path.c_str());
		lua_settable(L, top_lvl2);

		lua_pushstring(L,"name");
		lua_pushstring(L,worlds[i].name.c_str());
		lua_settable(L, top_lvl2);

		lua_pushstring(L,"gameid");
		lua_pushstring(L,worlds[i].gameid.c_str());
		lua_settable(L, top_lvl2);

		lua_settable(L, top);
		index++;
	}
	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_get_games(lua_State *L)
{
	std::vector<SubgameSpec> games = getAvailableGames();

	lua_newtable(L);
	int top = lua_gettop(L);
	unsigned int index = 1;

	for (unsigned int i = 0; i < games.size(); i++)
	{
		lua_pushnumber(L,index);
		lua_newtable(L);
		int top_lvl2 = lua_gettop(L);

		lua_pushstring(L,"id");
		lua_pushstring(L,games[i].id.c_str());
		lua_settable(L, top_lvl2);

		lua_pushstring(L,"path");
		lua_pushstring(L,games[i].path.c_str());
		lua_settable(L, top_lvl2);

		lua_pushstring(L,"gamemods_path");
		lua_pushstring(L,games[i].gamemods_path.c_str());
		lua_settable(L, top_lvl2);

		lua_pushstring(L,"name");
		lua_pushstring(L,games[i].name.c_str());
		lua_settable(L, top_lvl2);

		lua_pushstring(L,"menuicon_path");
		lua_pushstring(L,games[i].menuicon_path.c_str());
		lua_settable(L, top_lvl2);

		lua_pushstring(L,"addon_mods_paths");
		lua_newtable(L);
		int table2 = lua_gettop(L);
		int internal_index=1;
		for (std::set<std::string>::iterator iter = games[i].addon_mods_paths.begin();
				iter != games[i].addon_mods_paths.end(); ++iter) {
			lua_pushnumber(L,internal_index);
			lua_pushstring(L,(*iter).c_str());
			lua_settable(L, table2);
			internal_index++;
		}
		lua_settable(L, top_lvl2);
		lua_settable(L, top);
		index++;
	}
	return 1;
}
/******************************************************************************/
int ModApiMainMenu::l_get_modstore_details(lua_State *L)
{
	const char *modid	= luaL_checkstring(L, 1);

	if (modid != 0) {
		Json::Value details;
		std::string url = "";
		try{
			url = g_settings->get("modstore_details_url");
		}
		catch(SettingNotFoundException &e) {
			lua_pushnil(L);
			return 1;
		}

		size_t idpos = url.find("*");
		url.erase(idpos,1);
		url.insert(idpos,modid);

		details = getModstoreUrl(url);

		ModStoreModDetails current_mod = readModStoreModDetails(details);

		if ( current_mod.valid) {
			lua_newtable(L);
			int top = lua_gettop(L);

			lua_pushstring(L,"id");
			lua_pushnumber(L,current_mod.id);
			lua_settable(L, top);

			lua_pushstring(L,"title");
			lua_pushstring(L,current_mod.title.c_str());
			lua_settable(L, top);

			lua_pushstring(L,"basename");
			lua_pushstring(L,current_mod.basename.c_str());
			lua_settable(L, top);

			lua_pushstring(L,"description");
			lua_pushstring(L,current_mod.description.c_str());
			lua_settable(L, top);

			lua_pushstring(L,"author");
			lua_pushstring(L,current_mod.author.username.c_str());
			lua_settable(L, top);

			lua_pushstring(L,"download_url");
			lua_pushstring(L,current_mod.versions[0].file.c_str());
			lua_settable(L, top);

			lua_pushstring(L,"versions");
			lua_newtable(L);
			int versionstop = lua_gettop(L);
			for (unsigned int i=0;i < current_mod.versions.size(); i++) {
				lua_pushnumber(L,i+1);
				lua_newtable(L);
				int current_element = lua_gettop(L);

				lua_pushstring(L,"date");
				lua_pushstring(L,current_mod.versions[i].date.c_str());
				lua_settable(L,current_element);

				lua_pushstring(L,"download_url");
				lua_pushstring(L,current_mod.versions[i].file.c_str());
				lua_settable(L,current_element);

				lua_settable(L,versionstop);
			}
			lua_settable(L, top);

			lua_pushstring(L,"screenshot_url");
			lua_pushstring(L,current_mod.titlepic.file.c_str());
			lua_settable(L, top);

			lua_pushstring(L,"license");
			lua_pushstring(L,current_mod.license.shortinfo.c_str());
			lua_settable(L, top);

			lua_pushstring(L,"rating");
			lua_pushnumber(L,current_mod.rating);
			lua_settable(L, top);

			//TODO depends

			//TODO softdepends
			return 1;
		}
	}
	return 0;
}

/******************************************************************************/
int ModApiMainMenu::l_get_modstore_list(lua_State *L)
{
	Json::Value mods;
	std::string url = "";
	try{
		url = g_settings->get("modstore_listmods_url");
	}
	catch(SettingNotFoundException &e) {
		lua_pushnil(L);
		return 1;
	}

	mods = getModstoreUrl(url);

	std::vector<ModStoreMod> moddata = readModStoreList(mods);

	lua_newtable(L);
	int top = lua_gettop(L);
	unsigned int index = 1;

	for (unsigned int i = 0; i < moddata.size(); i++)
	{
		if (moddata[i].valid) {
			lua_pushnumber(L,index);
			lua_newtable(L);

			int top_lvl2 = lua_gettop(L);

			lua_pushstring(L,"id");
			lua_pushnumber(L,moddata[i].id);
			lua_settable(L, top_lvl2);

			lua_pushstring(L,"title");
			lua_pushstring(L,moddata[i].title.c_str());
			lua_settable(L, top_lvl2);

			lua_pushstring(L,"basename");
			lua_pushstring(L,moddata[i].basename.c_str());
			lua_settable(L, top_lvl2);

			lua_settable(L, top);
			index++;
		}
	}
	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_get_favorites(lua_State *L)
{
	std::string listtype = "local";

	if (!lua_isnone(L,1)) {
		listtype = luaL_checkstring(L,1);
	}

	std::vector<ServerListSpec> servers;

	if(listtype == "online") {
		servers = ServerList::getOnline();
	} else {
		servers = ServerList::getLocal();
	}

	lua_newtable(L);
	int top = lua_gettop(L);
	unsigned int index = 1;

	for (unsigned int i = 0; i < servers.size(); i++)
	{

		lua_pushnumber(L,index);

		lua_newtable(L);
		int top_lvl2 = lua_gettop(L);

		if (servers[i]["clients"].asString().size()) {
			std::string clients_raw = servers[i]["clients"].asString();
			char* endptr = 0;
			int numbervalue = strtol(clients_raw.c_str(),&endptr,10);

			if ((clients_raw != "") && (*endptr == 0)) {
				lua_pushstring(L,"clients");
				lua_pushnumber(L,numbervalue);
				lua_settable(L, top_lvl2);
			}
		}

		if (servers[i]["clients_max"].asString().size()) {

			std::string clients_max_raw = servers[i]["clients_max"].asString();
			char* endptr = 0;
			int numbervalue = strtol(clients_max_raw.c_str(),&endptr,10);

			if ((clients_max_raw != "") && (*endptr == 0)) {
				lua_pushstring(L,"clients_max");
				lua_pushnumber(L,numbervalue);
				lua_settable(L, top_lvl2);
			}
		}

		if (servers[i]["version"].asString().size()) {
			lua_pushstring(L,"version");
			std::string topush = servers[i]["version"].asString();
			lua_pushstring(L,topush.c_str());
			lua_settable(L, top_lvl2);
		}

		if (servers[i]["proto_min"].asString().size()) {
			lua_pushstring(L,"proto_min");
			lua_pushinteger(L,servers[i]["proto_min"].asInt());
			lua_settable(L, top_lvl2);
		}

		if (servers[i]["proto_max"].asString().size()) {
			lua_pushstring(L,"proto_max");
			lua_pushinteger(L,servers[i]["proto_max"].asInt());
			lua_settable(L, top_lvl2);
		}

		if (servers[i]["password"].asString().size()) {
			lua_pushstring(L,"password");
			lua_pushboolean(L,servers[i]["password"].asBool());
			lua_settable(L, top_lvl2);
		}

		if (servers[i]["creative"].asString().size()) {
			lua_pushstring(L,"creative");
			lua_pushboolean(L,servers[i]["creative"].asBool());
			lua_settable(L, top_lvl2);
		}

		if (servers[i]["damage"].asString().size()) {
			lua_pushstring(L,"damage");
			lua_pushboolean(L,servers[i]["damage"].asBool());
			lua_settable(L, top_lvl2);
		}

		if (servers[i]["pvp"].asString().size()) {
			lua_pushstring(L,"pvp");
			lua_pushboolean(L,servers[i]["pvp"].asBool());
			lua_settable(L, top_lvl2);
		}

		if (servers[i]["description"].asString().size()) {
			lua_pushstring(L,"description");
			std::string topush = servers[i]["description"].asString();
			lua_pushstring(L,topush.c_str());
			lua_settable(L, top_lvl2);
		}

		if (servers[i]["name"].asString().size()) {
			lua_pushstring(L,"name");
			std::string topush = servers[i]["name"].asString();
			lua_pushstring(L,topush.c_str());
			lua_settable(L, top_lvl2);
		}

		if (servers[i]["address"].asString().size()) {
			lua_pushstring(L,"address");
			std::string topush = servers[i]["address"].asString();
			lua_pushstring(L,topush.c_str());
			lua_settable(L, top_lvl2);
		}

		if (servers[i]["port"].asString().size()) {
			lua_pushstring(L,"port");
			std::string topush = servers[i]["port"].asString();
			lua_pushstring(L,topush.c_str());
			lua_settable(L, top_lvl2);
		}

		if (servers[i].isMember("ping")) {
			float ping = servers[i]["ping"].asFloat();
			lua_pushstring(L, "ping");
			lua_pushnumber(L, ping);
			lua_settable(L, top_lvl2);
		}

		lua_settable(L, top);
		index++;
	}
	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_delete_favorite(lua_State *L)
{
	std::vector<ServerListSpec> servers;

	std::string listtype = "local";

	if (!lua_isnone(L,2)) {
		listtype = luaL_checkstring(L,2);
	}

	if ((listtype != "local") &&
		(listtype != "online"))
		return 0;

	if(listtype == "online") {
		servers = ServerList::getOnline();
	} else {
		servers = ServerList::getLocal();
	}

	int fav_idx	= luaL_checkinteger(L,1) -1;

	if ((fav_idx >= 0) &&
			(fav_idx < (int) servers.size())) {

		ServerList::deleteEntry(servers[fav_idx]);
	}

	return 0;
}

/******************************************************************************/
int ModApiMainMenu::l_show_keys_menu(lua_State *L)
{
	GUIEngine* engine = getGuiEngine(L);
	sanity_check(engine != NULL);

	GUIKeyChangeMenu *kmenu
		= new GUIKeyChangeMenu(	engine->m_device->getGUIEnvironment(),
								engine->m_parent,
								-1,
								engine->m_menumanager);
	kmenu->drop();
	return 0;
}

/******************************************************************************/
int ModApiMainMenu::l_create_world(lua_State *L)
{
	const char *name	= luaL_checkstring(L, 1);
	int gameidx			= luaL_checkinteger(L,2) -1;

	std::string path = porting::path_user + DIR_DELIM
			"worlds" + DIR_DELIM
			+ name;

	std::vector<SubgameSpec> games = getAvailableGames();

	if ((gameidx >= 0) &&
			(gameidx < (int) games.size())) {

		// Create world if it doesn't exist
		if (!loadGameConfAndInitWorld(path, games[gameidx])) {
			lua_pushstring(L, "Failed to initialize world");
		} else {
			lua_pushnil(L);
		}
	} else {
		lua_pushstring(L, "Invalid game index");
	}
	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_delete_world(lua_State *L)
{
	int worldidx	= luaL_checkinteger(L,1) -1;

	std::vector<WorldSpec> worlds = getAvailableWorlds();

	if ((worldidx >= 0) &&
		(worldidx < (int) worlds.size())) {

		WorldSpec spec = worlds[worldidx];

		std::vector<std::string> paths;
		paths.push_back(spec.path);
		fs::GetRecursiveSubPaths(spec.path, paths);

		// Delete files
		if (!fs::DeletePaths(paths)) {
			lua_pushstring(L, "Failed to delete world");
		}
		else {
			lua_pushnil(L);
		}
	}
	else {
		lua_pushstring(L, "Invalid world index");
	}
	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_set_topleft_text(lua_State *L)
{
	GUIEngine* engine = getGuiEngine(L);
	sanity_check(engine != NULL);

	std::string text = "";

	if (!lua_isnone(L,1) &&	!lua_isnil(L,1))
		text = luaL_checkstring(L, 1);

	engine->setTopleftText(text);
	return 0;
}

/******************************************************************************/
int ModApiMainMenu::l_get_mapgen_names(lua_State *L)
{
	std::vector<const char *> names;
	Mapgen::getMapgenNames(&names, lua_toboolean(L, 1));

	lua_newtable(L);
	for (size_t i = 0; i != names.size(); i++) {
		lua_pushstring(L, names[i]);
		lua_rawseti(L, -2, i + 1);
	}

	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_get_modpath(lua_State *L)
{
	std::string modpath = fs::RemoveRelativePathComponents(
		porting::path_user + DIR_DELIM + "mods" + DIR_DELIM);
	lua_pushstring(L, modpath.c_str());
	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_get_gamepath(lua_State *L)
{
	std::string gamepath = fs::RemoveRelativePathComponents(
		porting::path_user + DIR_DELIM + "games" + DIR_DELIM);
	lua_pushstring(L, gamepath.c_str());
	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_get_texturepath(lua_State *L)
{
	std::string gamepath = fs::RemoveRelativePathComponents(
		porting::path_user + DIR_DELIM + "textures");
	lua_pushstring(L, gamepath.c_str());
	return 1;
}

int ModApiMainMenu::l_get_texturepath_share(lua_State *L)
{
	std::string gamepath = fs::RemoveRelativePathComponents(
		porting::path_share + DIR_DELIM + "textures");
	lua_pushstring(L, gamepath.c_str());
	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_create_dir(lua_State *L) {
	const char *path = luaL_checkstring(L, 1);

	if (ModApiMainMenu::isMinetestPath(path)) {
		lua_pushboolean(L, fs::CreateAllDirs(path));
		return 1;
	}

	lua_pushboolean(L, false);
	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_delete_dir(lua_State *L)
{
	const char *path = luaL_checkstring(L, 1);

	std::string absolute_path = fs::RemoveRelativePathComponents(path);

	if (ModApiMainMenu::isMinetestPath(absolute_path)) {
		lua_pushboolean(L, fs::RecursiveDelete(absolute_path));
		return 1;
	}

	lua_pushboolean(L, false);
	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_copy_dir(lua_State *L)
{
	const char *source	= luaL_checkstring(L, 1);
	const char *destination	= luaL_checkstring(L, 2);

	bool keep_source = true;

	if ((!lua_isnone(L,3)) &&
			(!lua_isnil(L,3))) {
		keep_source = lua_toboolean(L,3);
	}

	std::string absolute_destination = fs::RemoveRelativePathComponents(destination);
	std::string absolute_source = fs::RemoveRelativePathComponents(source);

	if ((ModApiMainMenu::isMinetestPath(absolute_source)) &&
			(ModApiMainMenu::isMinetestPath(absolute_destination))) {
		bool retval = fs::CopyDir(absolute_source,absolute_destination);

		if (retval && (!keep_source)) {

			retval &= fs::RecursiveDelete(absolute_source);
		}
		lua_pushboolean(L,retval);
		return 1;
	}
	lua_pushboolean(L,false);
	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_extract_zip(lua_State *L)
{
	GUIEngine* engine = getGuiEngine(L);
	sanity_check(engine);

	const char *zipfile	= luaL_checkstring(L, 1);
	const char *destination	= luaL_checkstring(L, 2);

	std::string absolute_destination = fs::RemoveRelativePathComponents(destination);

	if (ModApiMainMenu::isMinetestPath(absolute_destination)) {
		fs::CreateAllDirs(absolute_destination);

		io::IFileSystem* fs = engine->m_device->getFileSystem();

		if (!fs->addFileArchive(zipfile,true,false,io::EFAT_ZIP)) {
			lua_pushboolean(L,false);
			return 1;
		}

		sanity_check(fs->getFileArchiveCount() > 0);

		/**********************************************************************/
		/* WARNING this is not threadsafe!!                                   */
		/**********************************************************************/
		io::IFileArchive* opened_zip =
			fs->getFileArchive(fs->getFileArchiveCount()-1);

		const io::IFileList* files_in_zip = opened_zip->getFileList();

		unsigned int number_of_files = files_in_zip->getFileCount();

		for (unsigned int i=0; i < number_of_files; i++) {
			std::string fullpath = destination;
			fullpath += DIR_DELIM;
			fullpath += files_in_zip->getFullFileName(i).c_str();
			std::string fullpath_dir = fs::RemoveLastPathComponent(fullpath);

			if (!files_in_zip->isDirectory(i)) {
				if (!fs::PathExists(fullpath_dir) && !fs::CreateAllDirs(fullpath_dir)) {
					fs->removeFileArchive(fs->getFileArchiveCount()-1);
					lua_pushboolean(L,false);
					return 1;
				}

				io::IReadFile* toread = opened_zip->createAndOpenFile(i);

				FILE *targetfile = fopen(fullpath.c_str(),"wb");

				if (targetfile == NULL) {
					fs->removeFileArchive(fs->getFileArchiveCount()-1);
					lua_pushboolean(L,false);
					return 1;
				}

				char read_buffer[1024];
				long total_read = 0;

				while (total_read < toread->getSize()) {

					unsigned int bytes_read =
							toread->read(read_buffer,sizeof(read_buffer));
					if ((bytes_read == 0 ) ||
						(fwrite(read_buffer, 1, bytes_read, targetfile) != bytes_read))
					{
						fclose(targetfile);
						fs->removeFileArchive(fs->getFileArchiveCount()-1);
						lua_pushboolean(L,false);
						return 1;
					}
					total_read += bytes_read;
				}

				fclose(targetfile);
			}

		}

		fs->removeFileArchive(fs->getFileArchiveCount()-1);
		lua_pushboolean(L,true);
		return 1;
	}

	lua_pushboolean(L,false);
	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_get_mainmenu_path(lua_State *L)
{
	GUIEngine* engine = getGuiEngine(L);
	sanity_check(engine != NULL);

	lua_pushstring(L,engine->getScriptDir().c_str());
	return 1;
}

/******************************************************************************/
bool ModApiMainMenu::isMinetestPath(std::string path)
{
	if (fs::PathStartsWith(path,fs::TempPath()))
		return true;

	/* games */
	if (fs::PathStartsWith(path,fs::RemoveRelativePathComponents(porting::path_share + DIR_DELIM + "games")))
		return true;

	/* mods */
	if (fs::PathStartsWith(path,fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM + "mods")))
		return true;

	/* worlds */
	if (fs::PathStartsWith(path,fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM + "worlds")))
		return true;

	return false;
}

/******************************************************************************/
int ModApiMainMenu::l_show_file_open_dialog(lua_State *L)
{
	GUIEngine* engine = getGuiEngine(L);
	sanity_check(engine != NULL);

	const char *formname= luaL_checkstring(L, 1);
	const char *title	= luaL_checkstring(L, 2);

	GUIFileSelectMenu* fileOpenMenu =
		new GUIFileSelectMenu(engine->m_device->getGUIEnvironment(),
								engine->m_parent,
								-1,
								engine->m_menumanager,
								title,
								formname);
	fileOpenMenu->setTextDest(engine->m_buttonhandler);
	fileOpenMenu->drop();
	return 0;
}

/******************************************************************************/
int ModApiMainMenu::l_download_file(lua_State *L)
{
	const char *url    = luaL_checkstring(L, 1);
	const char *target = luaL_checkstring(L, 2);

	//check path
	std::string absolute_destination = fs::RemoveRelativePathComponents(target);

	if (ModApiMainMenu::isMinetestPath(absolute_destination)) {
		if (GUIEngine::downloadFile(url,absolute_destination)) {
			lua_pushboolean(L,true);
			return 1;
		}
	} else {
		errorstream << "DOWNLOAD denied: " << absolute_destination
				<< " isn't a allowed path" << std::endl;
	}
	lua_pushboolean(L,false);
	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_get_video_drivers(lua_State *L)
{
	std::vector<irr::video::E_DRIVER_TYPE> drivers
		= porting::getSupportedVideoDrivers();

	lua_newtable(L);
	for (u32 i = 0; i != drivers.size(); i++) {
		const char *name  = porting::getVideoDriverName(drivers[i]);
		const char *fname = porting::getVideoDriverFriendlyName(drivers[i]);

		lua_newtable(L);
		lua_pushstring(L, name);
		lua_setfield(L, -2, "name");
		lua_pushstring(L, fname);
		lua_setfield(L, -2, "friendly_name");

		lua_rawseti(L, -2, i + 1);
	}

	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_get_video_modes(lua_State *L)
{
	std::vector<core::vector3d<u32> > videomodes
		= porting::getSupportedVideoModes();

	lua_newtable(L);
	for (u32 i = 0; i != videomodes.size(); i++) {
		lua_newtable(L);
		lua_pushnumber(L, videomodes[i].X);
		lua_setfield(L, -2, "w");
		lua_pushnumber(L, videomodes[i].Y);
		lua_setfield(L, -2, "h");
		lua_pushnumber(L, videomodes[i].Z);
		lua_setfield(L, -2, "depth");

		lua_rawseti(L, -2, i + 1);
	}

	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_gettext(lua_State *L)
{
	std::string text = strgettext(std::string(luaL_checkstring(L, 1)));
	lua_pushstring(L, text.c_str());

	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_get_screen_info(lua_State *L)
{
	lua_newtable(L);
	int top = lua_gettop(L);
	lua_pushstring(L,"density");
	lua_pushnumber(L,porting::getDisplayDensity());
	lua_settable(L, top);

	lua_pushstring(L,"display_width");
	lua_pushnumber(L,porting::getDisplaySize().X);
	lua_settable(L, top);

	lua_pushstring(L,"display_height");
	lua_pushnumber(L,porting::getDisplaySize().Y);
	lua_settable(L, top);

	lua_pushstring(L,"window_width");
	lua_pushnumber(L,porting::getWindowSize().X);
	lua_settable(L, top);

	lua_pushstring(L,"window_height");
	lua_pushnumber(L,porting::getWindowSize().Y);
	lua_settable(L, top);
	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_get_min_supp_proto(lua_State *L)
{
	u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
		CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
	lua_pushinteger(L, proto_version_min);
	return 1;
}

int ModApiMainMenu::l_get_max_supp_proto(lua_State *L)
{
	lua_pushinteger(L, CLIENT_PROTOCOL_VERSION_MAX);
	return 1;
}

/******************************************************************************/
int ModApiMainMenu::l_do_async_callback(lua_State *L)
{
	GUIEngine* engine = getGuiEngine(L);

	size_t func_length, param_length;
	const char* serialized_func_raw = luaL_checklstring(L, 1, &func_length);

	const char* serialized_param_raw = luaL_checklstring(L, 2, &param_length);

	sanity_check(serialized_func_raw != NULL);
	sanity_check(serialized_param_raw != NULL);

	std::string serialized_func = std::string(serialized_func_raw, func_length);
	std::string serialized_param = std::string(serialized_param_raw, param_length);

	lua_pushinteger(L, engine->queueAsync(serialized_func, serialized_param));

	return 1;
}

/******************************************************************************/
void ModApiMainMenu::Initialize(lua_State *L, int top)
{
	API_FCT(update_formspec);
	API_FCT(set_clouds);
	API_FCT(get_textlist_index);
	API_FCT(get_table_index);
	API_FCT(get_worlds);
	API_FCT(get_games);
	API_FCT(start);
	API_FCT(close);
	API_FCT(get_favorites);
	API_FCT(show_keys_menu);
	API_FCT(create_world);
	API_FCT(delete_world);
	API_FCT(delete_favorite);
	API_FCT(set_background);
	API_FCT(set_topleft_text);
	API_FCT(get_mapgen_names);
	API_FCT(get_modpath);
	API_FCT(get_gamepath);
	API_FCT(get_texturepath);
	API_FCT(get_texturepath_share);
	API_FCT(create_dir);
	API_FCT(delete_dir);
	API_FCT(copy_dir);
	API_FCT(extract_zip);
	API_FCT(get_mainmenu_path);
	API_FCT(show_file_open_dialog);
	API_FCT(download_file);
	API_FCT(get_modstore_details);
	API_FCT(get_modstore_list);
	API_FCT(gettext);
	API_FCT(get_video_drivers);
	API_FCT(get_video_modes);
	API_FCT(get_screen_info);
	API_FCT(get_min_supp_proto);
	API_FCT(get_max_supp_proto);
	API_FCT(do_async_callback);
}

/******************************************************************************/
void ModApiMainMenu::InitializeAsync(lua_State *L, int top)
{

	API_FCT(get_worlds);
	API_FCT(get_games);
	API_FCT(get_favorites);
	API_FCT(get_mapgen_names);
	API_FCT(get_modpath);
	API_FCT(get_gamepath);
	API_FCT(get_texturepath);
	API_FCT(get_texturepath_share);
	API_FCT(create_dir);
	API_FCT(delete_dir);
	API_FCT(copy_dir);
	//API_FCT(extract_zip); //TODO remove dependency to GuiEngine
	API_FCT(download_file);
	API_FCT(get_modstore_details);
	API_FCT(get_modstore_list);
	//API_FCT(gettext); (gettext lib isn't threadsafe)
}

repo_name: pgimeno/minetest

license: unknown


code:
/*
Minetest
Copyright (C) 2013 sapier

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#ifndef L_MAINMENU_H_
#define L_MAINMENU_H_

#include "lua_api/l_base.h"

class AsyncEngine;

/** Implementation of lua api support for mainmenu */
class ModApiMainMenu: public ModApiBase
{

private:
	/**
	 * read a text variable from gamedata table within lua stack
	 * @param L stack to read variable from
	 * @param name name of variable to read
	 * @return string value of requested variable
	 */
	static std::string getTextData(lua_State *L, std::string name);

	/**
	 * read a integer variable from gamedata table within lua stack
	 * @param L stack to read variable from
	 * @param name name of variable to read
	 * @return integer value of requested variable
	 */
	static int getIntegerData(lua_State *L, std::string name,bool& valid);

	/**
	 * read a bool variable from gamedata table within lua stack
	 * @param L stack to read variable from
	 * @param name name of variable to read
	 * @return bool value of requested variable
	 */
	static int getBoolData(lua_State *L, std::string name,bool& valid);

	/**
	 * check if a path is within some of minetests folders
	 * @param path path to check
	 * @return true/false
	 */
	static bool isMinetestPath(std::string path);

	//api calls

	static int l_start(lua_State *L);

	static int l_close(lua_State *L);

	static int l_create_world(lua_State *L);

	static int l_delete_world(lua_State *L);

	static int l_get_worlds(lua_State *L);

	static int l_get_games(lua_State *L);

	static int l_get_mapgen_names(lua_State *L);

	static int l_get_favorites(lua_State *L);

	static int l_delete_favorite(lua_State *L);

	static int l_gettext(lua_State *L);

	//gui

	static int l_show_keys_menu(lua_State *L);

	static int l_show_file_open_dialog(lua_State *L);

	static int l_set_topleft_text(lua_State *L);

	static int l_set_clouds(lua_State *L);

	static int l_get_textlist_index(lua_State *L);

	static int l_get_table_index(lua_State *L);

	static int l_set_background(lua_State *L);

	static int l_update_formspec(lua_State *L);

	static int l_get_screen_info(lua_State *L);

	//filesystem

	static int l_get_mainmenu_path(lua_State *L);

	static int l_get_modpath(lua_State *L);

	static int l_get_gamepath(lua_State *L);

	static int l_get_texturepath(lua_State *L);

	static int l_get_texturepath_share(lua_State *L);

	static int l_create_dir(lua_State *L);

	static int l_delete_dir(lua_State *L);

	static int l_copy_dir(lua_State *L);

	static int l_extract_zip(lua_State *L);

	static int l_get_modstore_details(lua_State *L);

	static int l_get_modstore_list(lua_State *L);

	static int l_download_file(lua_State *L);

	static int l_get_video_drivers(lua_State *L);

	static int l_get_video_modes(lua_State *L);

	//version compatibility
	static int l_get_min_supp_proto(lua_State *L);

	static int l_get_max_supp_proto(lua_State *L);

	// async
	static int l_do_async_callback(lua_State *L);

public:

	/**
	 * initialize this API module
	 * @param L lua stack to initialize
	 * @param top index (in lua stack) of global API table
	 */
	static void Initialize(lua_State *L, int top);

	static void InitializeAsync(lua_State *L, int top);

};

#endif /* L_MAINMENU_H_ */


code:
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "lua_api/l_mapgen.h"
#include "lua_api/l_internal.h"
#include "lua_api/l_vmanip.h"
#include "common/c_converter.h"
#include "common/c_content.h"
#include "cpp_api/s_security.h"
#include "util/serialize.h"
#include "server.h"
#include "environment.h"
#include "emerge.h"
#include "mg_biome.h"
#include "mg_ore.h"
#include "mg_decoration.h"
#include "mg_schematic.h"
#include "mapgen_v5.h"
#include "mapgen_v7.h"
#include "filesys.h"
#include "settings.h"
#include "log.h"

struct EnumString ModApiMapgen::es_BiomeTerrainType[] =
{
	{BIOMETYPE_NORMAL, "normal"},
	{BIOMETYPE_LIQUID, "liquid"},
	{BIOMETYPE_NETHER, "nether"},
	{BIOMETYPE_AETHER, "aether"},
	{BIOMETYPE_FLAT,   "flat"},
	{0, NULL},
};

struct EnumString ModApiMapgen::es_DecorationType[] =
{
	{DECO_SIMPLE,    "simple"},
	{DECO_SCHEMATIC, "schematic"},
	{DECO_LSYSTEM,   "lsystem"},
	{0, NULL},
};

struct EnumString ModApiMapgen::es_MapgenObject[] =
{
	{MGOBJ_VMANIP,    "voxelmanip"},
	{MGOBJ_HEIGHTMAP, "heightmap"},
	{MGOBJ_BIOMEMAP,  "biomemap"},
	{MGOBJ_HEATMAP,   "heatmap"},
	{MGOBJ_HUMIDMAP,  "humiditymap"},
	{MGOBJ_GENNOTIFY, "gennotify"},
	{0, NULL},
};

struct EnumString ModApiMapgen::es_OreType[] =
{
	{ORE_SCATTER, "scatter"},
	{ORE_SHEET,   "sheet"},
	{ORE_PUFF,    "puff"},
	{ORE_BLOB,    "blob"},
	{ORE_VEIN,    "vein"},
	{0, NULL},
};

struct EnumString ModApiMapgen::es_Rotation[] =
{
	{ROTATE_0,    "0"},
	{ROTATE_90,   "90"},
	{ROTATE_180,  "180"},
	{ROTATE_270,  "270"},
	{ROTATE_RAND, "random"},
	{0, NULL},
};

struct EnumString ModApiMapgen::es_SchematicFormatType[] =
{
	{SCHEM_FMT_HANDLE, "handle"},
	{SCHEM_FMT_MTS,    "mts"},
	{SCHEM_FMT_LUA,    "lua"},
	{0, NULL},
};

ObjDef *get_objdef(lua_State *L, int index, ObjDefManager *objmgr);

Biome *get_or_load_biome(lua_State *L, int index,
	BiomeManager *biomemgr);
Biome *read_biome_def(lua_State *L, int index, INodeDefManager *ndef);
size_t get_biome_list(lua_State *L, int index,
	BiomeManager *biomemgr, UNORDERED_SET<u8> *biome_id_list);

Schematic *get_or_load_schematic(lua_State *L, int index,
	SchematicManager *schemmgr, StringMap *replace_names);
Schematic *load_schematic(lua_State *L, int index, INodeDefManager *ndef,
	StringMap *replace_names);
Schematic *load_schematic_from_def(lua_State *L, int index,
	INodeDefManager *ndef, StringMap *replace_names);
bool read_schematic_def(lua_State *L, int index,
	Schematic *schem, std::vector<std::string> *names);

bool read_deco_simple(lua_State *L, DecoSimple *deco);
bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco);

///////////////////////////////////////////////////////////////////////////////

ObjDef *get_objdef(lua_State *L, int index, ObjDefManager *objmgr)
{
	if (index < 0)
		index = lua_gettop(L) + 1 + index;

	// If a number, assume this is a handle to an object def
	if (lua_isnumber(L, index))
		return objmgr->get(lua_tointeger(L, index));

	// If a string, assume a name is given instead
	if (lua_isstring(L, index))
		return objmgr->getByName(lua_tostring(L, index));

	return NULL;
}

///////////////////////////////////////////////////////////////////////////////

Schematic *get_or_load_schematic(lua_State *L, int index,
	SchematicManager *schemmgr, StringMap *replace_names)
{
	if (index < 0)
		index = lua_gettop(L) + 1 + index;

	Schematic *schem = (Schematic *)get_objdef(L, index, schemmgr);
	if (schem)
		return schem;

	schem = load_schematic(L, index, schemmgr->getNodeDef(),
		replace_names);
	if (!schem)
		return NULL;

	if (schemmgr->add(schem) == OBJDEF_INVALID_HANDLE) {
		delete schem;
		return NULL;
	}

	return schem;
}

Schematic *load_schematic(lua_State *L, int index, INodeDefManager *ndef,
	StringMap *replace_names)
{
	if (index < 0)
		index = lua_gettop(L) + 1 + index;

	Schematic *schem = NULL;

	if (lua_istable(L, index)) {
		schem = load_schematic_from_def(L, index, ndef,
			replace_names);
		if (!schem) {
			delete schem;
			return NULL;
		}
	} else if (lua_isnumber(L, index)) {
		return NULL;
	} else if (lua_isstring(L, index)) {
		schem = SchematicManager::create(SCHEMATIC_NORMAL);

		std::string filepath = lua_tostring(L, index);
		if (!fs::IsPathAbsolute(filepath))
			filepath = ModApiBase::getCurrentModPath(L) + DIR_DELIM + filepath;

		if (!schem->loadSchematicFromFile(filepath, ndef,
				replace_names)) {
			delete schem;
			return NULL;
		}
	}

	return schem;
}

Schematic *load_schematic_from_def(lua_State *L, int index,
	INodeDefManager *ndef, StringMap *replace_names)
{
	Schematic *schem = SchematicManager::create(SCHEMATIC_NORMAL);

	if (!read_schematic_def(L, index, schem, &schem->m_nodenames)) {
		delete schem;
		return NULL;
	}

	size_t num_nodes = schem->m_nodenames.size();

	schem->m_nnlistsizes.push_back(num_nodes);

	if (replace_names) {
		for (size_t i = 0; i != num_nodes; i++) {
			StringMap::iterator it = replace_names->find(schem->m_nodenames[i]);
			if (it != replace_names->end())
				schem->m_nodenames[i] = it->second;
		}
	}

	if (ndef)
		ndef->pendNodeResolve(schem);

	return schem;
}

bool read_schematic_def(lua_State *L, int index,
	Schematic *schem, std::vector<std::string> *names)
{
	if (!lua_istable(L, index))
		return false;

	//// Get schematic size
	lua_getfield(L, index, "size");
	v3s16 size = check_v3s16(L, -1);
	lua_pop(L, 1);

	schem->size = size;

	//// Get schematic data
	lua_getfield(L, index, "data");
	luaL_checktype(L, -1, LUA_TTABLE);

	u32 numnodes = size.X * size.Y * size.Z;
	schem->schemdata = new MapNode[numnodes];

	size_t names_base = names->size();
	UNORDERED_MAP<std::string, content_t> name_id_map;

	u32 i = 0;
	for (lua_pushnil(L); lua_next(L, -2); i++, lua_pop(L, 1)) {
		if (i >= numnodes)
			continue;

		//// Read name
		std::string name;
		if (!getstringfield(L, -1, "name", name))
			throw LuaError("Schematic data definition with missing name field");

		//// Read param1/prob
		u8 param1;
		if (!getintfield(L, -1, "param1", param1) &&
			!getintfield(L, -1, "prob", param1))
			param1 = MTSCHEM_PROB_ALWAYS_OLD;

		//// Read param2
		u8 param2 = getintfield_default(L, -1, "param2", 0);

		//// Find or add new nodename-to-ID mapping
		UNORDERED_MAP<std::string, content_t>::iterator it = name_id_map.find(name);
		content_t name_index;
		if (it != name_id_map.end()) {
			name_index = it->second;
		} else {
			name_index = names->size() - names_base;
			name_id_map[name] = name_index;
			names->push_back(name);
		}

		//// Perform probability/force_place fixup on param1
		param1 >>= 1;
		if (getboolfield_default(L, -1, "force_place", false))
			param1 |= MTSCHEM_FORCE_PLACE;

		//// Actually set the node in the schematic
		schem->schemdata[i] = MapNode(name_index, param1, param2);
	}

	if (i != numnodes) {
		errorstream << "read_schematic_def: incorrect number of "
			"nodes provided in raw schematic data (got " << i <<
			", expected " << numnodes << ")." << std::endl;
		return false;
	}

	//// Get Y-slice probability values (if present)
	schem->slice_probs = new u8[size.Y];
	for (i = 0; i != (u32) size.Y; i++)
		schem->slice_probs[i] = MTSCHEM_PROB_ALWAYS;

	lua_getfield(L, index, "yslice_prob");
	if (lua_istable(L, -1)) {
		for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
			u16 ypos;
			if (!getintfield(L, -1, "ypos", ypos) || (ypos >= size.Y) ||
				!getintfield(L, -1, "prob", schem->slice_probs[ypos]))
				continue;

			schem->slice_probs[ypos] >>= 1;
		}
	}

	return true;
}

void read_schematic_replacements(lua_State *L, int index, StringMap *replace_names)
{
	if (index < 0)
		index = lua_gettop(L) + 1 + index;

	lua_pushnil(L);
	while (lua_next(L, index)) {
		std::string replace_from;
		std::string replace_to;

		if (lua_istable(L, -1)) { // Old {{"x", "y"}, ...} format
			lua_rawgeti(L, -1, 1);
			if (!lua_isstring(L, -1))
				throw LuaError("schematics: replace_from field is not a string");
			replace_from = lua_tostring(L, -1);
			lua_pop(L, 1);

			lua_rawgeti(L, -1, 2);
			if (!lua_isstring(L, -1))
				throw LuaError("schematics: replace_to field is not a string");
			replace_to = lua_tostring(L, -1);
			lua_pop(L, 1);
		} else { // New {x = "y", ...} format
			if (!lua_isstring(L, -2))
				throw LuaError("schematics: replace_from field is not a string");
			replace_from = lua_tostring(L, -2);
			if (!lua_isstring(L, -1))
				throw LuaError("schematics: replace_to field is not a string");
			replace_to = lua_tostring(L, -1);
		}

		replace_names->insert(std::make_pair(replace_from, replace_to));
		lua_pop(L, 1);
	}
}

///////////////////////////////////////////////////////////////////////////////

Biome *get_or_load_biome(lua_State *L, int index, BiomeManager *biomemgr)
{
	if (index < 0)
		index = lua_gettop(L) + 1 + index;

	Biome *biome = (Biome *)get_objdef(L, index, biomemgr);
	if (biome)
		return biome;

	biome = read_biome_def(L, index, biomemgr->getNodeDef());
	if (!biome)
		return NULL;

	if (biomemgr->add(biome) == OBJDEF_INVALID_HANDLE) {
		delete biome;
		return NULL;
	}

	return biome;
}

Biome *read_biome_def(lua_State *L, int index, INodeDefManager *ndef)
{
	if (!lua_istable(L, index))
		return NULL;

	BiomeType biometype = (BiomeType)getenumfield(L, index, "type",
		ModApiMapgen::es_BiomeTerrainType, BIOMETYPE_NORMAL);
	Biome *b = BiomeManager::create(biometype);

	b->name            = getstringfield_default(L, index, "name", "");
	b->depth_top       = getintfield_default(L,    index, "depth_top",       0);
	b->depth_filler    = getintfield_default(L,    index, "depth_filler",    -31000);
	b->depth_water_top = getintfield_default(L,    index, "depth_water_top", 0);
	b->depth_riverbed  = getintfield_default(L,    index, "depth_riverbed",  0);
	b->y_min           = getintfield_default(L,    index, "y_min",           -31000);
	b->y_max           = getintfield_default(L,    index, "y_max",           31000);
	b->heat_point      = getfloatfield_default(L,  index, "heat_point",      0.f);
	b->humidity_point  = getfloatfield_default(L,  index, "humidity_point",  0.f);
	b->flags           = 0; //reserved

	std::vector<std::string> &nn = b->m_nodenames;
	nn.push_back(getstringfield_default(L, index, "node_top",         ""));
	nn.push_back(getstringfield_default(L, index, "node_filler",      ""));
	nn.push_back(getstringfield_default(L, index, "node_stone",       ""));
	nn.push_back(getstringfield_default(L, index, "node_water_top",   ""));
	nn.push_back(getstringfield_default(L, index, "node_water",       ""));
	nn.push_back(getstringfield_default(L, index, "node_river_water", ""));
	nn.push_back(getstringfield_default(L, index, "node_riverbed",    ""));
	nn.push_back(getstringfield_default(L, index, "node_dust",        ""));
	ndef->pendNodeResolve(b);

	return b;
}

size_t get_biome_list(lua_State *L, int index,
	BiomeManager *biomemgr, UNORDERED_SET<u8> *biome_id_list)
{
	if (index < 0)
		index = lua_gettop(L) + 1 + index;

	if (lua_isnil(L, index))
		return 0;

	bool is_single = true;
	if (lua_istable(L, index)) {
		lua_getfield(L, index, "name");
		is_single = !lua_isnil(L, -1);
		lua_pop(L, 1);
	}

	if (is_single) {
		Biome *biome = get_or_load_biome(L, index, biomemgr);
		if (!biome) {
			infostream << "get_biome_list: failed to get biome '"
				<< (lua_isstring(L, index) ? lua_tostring(L, index) : "")
				<< "'." << std::endl;
			return 1;
		}

		biome_id_list->insert(biome->index);
		return 0;
	}

	// returns number of failed resolutions
	size_t fail_count = 0;
	size_t count = 0;

	for (lua_pushnil(L); lua_next(L, index); lua_pop(L, 1)) {
		count++;
		Biome *biome = get_or_load_biome(L, -1, biomemgr);
		if (!biome) {
			fail_count++;
			infostream << "get_biome_list: failed to get biome '"
				<< (lua_isstring(L, -1) ? lua_tostring(L, -1) : "")
				<< "'" << std::endl;
			continue;
		}

		biome_id_list->insert(biome->index);
	}

	return fail_count;
}

///////////////////////////////////////////////////////////////////////////////

// get_biome_id(biomename)
// returns the biome id used in biomemap
int ModApiMapgen::l_get_biome_id(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	const char *biome_str = lua_tostring(L, 1);
	if (!biome_str)
		return 0;

	BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr;

	if (!bmgr)
		return 0;

	Biome *biome = (Biome *)bmgr->getByName(biome_str);

	if (!biome || biome->index == OBJDEF_INVALID_INDEX)
		return 0;

	lua_pushinteger(L, biome->index);

	return 1;
}

// get_mapgen_object(objectname)
// returns the requested object used during map generation
int ModApiMapgen::l_get_mapgen_object(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	const char *mgobjstr = lua_tostring(L, 1);

	int mgobjint;
	if (!string_to_enum(es_MapgenObject, mgobjint, mgobjstr ? mgobjstr : ""))
		return 0;

	enum MapgenObject mgobj = (MapgenObject)mgobjint;

	EmergeManager *emerge = getServer(L)->getEmergeManager();
	Mapgen *mg = emerge->getCurrentMapgen();
	if (!mg)
		throw LuaError("Must only be called in a mapgen thread!");

	size_t maplen = mg->csize.X * mg->csize.Z;

	switch (mgobj) {
	case MGOBJ_VMANIP: {
		MMVManip *vm = mg->vm;

		// VoxelManip object
		LuaVoxelManip *o = new LuaVoxelManip(vm, true);
		*(void **)(lua_newuserdata(L, sizeof(void *))) = o;
		luaL_getmetatable(L, "VoxelManip");
		lua_setmetatable(L, -2);

		// emerged min pos
		push_v3s16(L, vm->m_area.MinEdge);

		// emerged max pos
		push_v3s16(L, vm->m_area.MaxEdge);

		return 3;
	}
	case MGOBJ_HEIGHTMAP: {
		if (!mg->heightmap)
			return 0;

		lua_newtable(L);
		for (size_t i = 0; i != maplen; i++) {
			lua_pushinteger(L, mg->heightmap[i]);
			lua_rawseti(L, -2, i + 1);
		}

		return 1;
	}
	case MGOBJ_BIOMEMAP: {
		if (!mg->biomegen)
			return 0;

		lua_newtable(L);
		for (size_t i = 0; i != maplen; i++) {
			lua_pushinteger(L, mg->biomegen->biomemap[i]);
			lua_rawseti(L, -2, i + 1);
		}

		return 1;
	}
	case MGOBJ_HEATMAP: {
		if (!mg->biomegen || mg->biomegen->getType() != BIOMEGEN_ORIGINAL)
			return 0;

		BiomeGenOriginal *bg = (BiomeGenOriginal *)mg->biomegen;

		lua_newtable(L);
		for (size_t i = 0; i != maplen; i++) {
			lua_pushnumber(L, bg->heatmap[i]);
			lua_rawseti(L, -2, i + 1);
		}

		return 1;
	}

	case MGOBJ_HUMIDMAP: {
		if (!mg->biomegen || mg->biomegen->getType() != BIOMEGEN_ORIGINAL)
			return 0;

		BiomeGenOriginal *bg = (BiomeGenOriginal *)mg->biomegen;

		lua_newtable(L);
		for (size_t i = 0; i != maplen; i++) {
			lua_pushnumber(L, bg->humidmap[i]);
			lua_rawseti(L, -2, i + 1);
		}

		return 1;
	}
	case MGOBJ_GENNOTIFY: {
		std::map<std::string, std::vector<v3s16> >event_map;
		std::map<std::string, std::vector<v3s16> >::iterator it;

		mg->gennotify.getEvents(event_map);

		lua_newtable(L);
		for (it = event_map.begin(); it != event_map.end(); ++it) {
			lua_newtable(L);

			for (size_t j = 0; j != it->second.size(); j++) {
				push_v3s16(L, it->second[j]);
				lua_rawseti(L, -2, j + 1);
			}

			lua_setfield(L, -2, it->first.c_str());
		}

		return 1;
	}
	}

	return 0;
}

int ModApiMapgen::l_get_mapgen_params(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	log_deprecated(L, "get_mapgen_params is deprecated; "
		"use get_mapgen_setting instead");

	std::string value;

	MapSettingsManager *settingsmgr =
		getServer(L)->getEmergeManager()->map_settings_mgr;

	lua_newtable(L);

	settingsmgr->getMapSetting("mg_name", &value);
	lua_pushstring(L, value.c_str());
	lua_setfield(L, -2, "mgname");

	settingsmgr->getMapSetting("seed", &value);
	std::istringstream ss(value);
	u64 seed;
	ss >> seed;
	lua_pushinteger(L, seed);
	lua_setfield(L, -2, "seed");

	settingsmgr->getMapSetting("water_level", &value);
	lua_pushinteger(L, stoi(value, -32768, 32767));
	lua_setfield(L, -2, "water_level");

	settingsmgr->getMapSetting("chunksize", &value);
	lua_pushinteger(L, stoi(value, -32768, 32767));
	lua_setfield(L, -2, "chunksize");

	settingsmgr->getMapSetting("mg_flags", &value);
	lua_pushstring(L, value.c_str());
	lua_setfield(L, -2, "flags");

	return 1;
}

// set_mapgen_params(params)
// set mapgen parameters
int ModApiMapgen::l_set_mapgen_params(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	log_deprecated(L, "set_mapgen_params is deprecated; "
		"use set_mapgen_setting instead");

	if (!lua_istable(L, 1))
		return 0;

	MapSettingsManager *settingsmgr =
		getServer(L)->getEmergeManager()->map_settings_mgr;

	lua_getfield(L, 1, "mgname");
	if (lua_isstring(L, -1))
		settingsmgr->setMapSetting("mg_name", lua_tostring(L, -1), true);

	lua_getfield(L, 1, "seed");
	if (lua_isnumber(L, -1))
		settingsmgr->setMapSetting("seed", lua_tostring(L, -1), true);

	lua_getfield(L, 1, "water_level");
	if (lua_isnumber(L, -1))
		settingsmgr->setMapSetting("water_level", lua_tostring(L, -1), true);

	lua_getfield(L, 1, "chunksize");
	if (lua_isnumber(L, -1))
		settingsmgr->setMapSetting("chunksize", lua_tostring(L, -1), true);

	warn_if_field_exists(L, 1, "flagmask",
		"Deprecated: flags field now includes unset flags.");

	lua_getfield(L, 1, "flags");
	if (lua_isstring(L, -1))
		settingsmgr->setMapSetting("mg_flags", lua_tostring(L, -1), true);

	return 0;
}

// get_mapgen_setting(name)
int ModApiMapgen::l_get_mapgen_setting(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	std::string value;
	MapSettingsManager *settingsmgr =
		getServer(L)->getEmergeManager()->map_settings_mgr;

	const char *name = luaL_checkstring(L, 1);
	if (!settingsmgr->getMapSetting(name, &value))
		return 0;

	lua_pushstring(L, value.c_str());
	return 1;
}

// get_mapgen_setting_noiseparams(name)
int ModApiMapgen::l_get_mapgen_setting_noiseparams(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	NoiseParams np;
	MapSettingsManager *settingsmgr =
		getServer(L)->getEmergeManager()->map_settings_mgr;

	const char *name = luaL_checkstring(L, 1);
	if (!settingsmgr->getMapSettingNoiseParams(name, &np))
		return 0;

	push_noiseparams(L, &np);
	return 1;
}

// set_mapgen_setting(name, value, override_meta)
// set mapgen config values
int ModApiMapgen::l_set_mapgen_setting(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	MapSettingsManager *settingsmgr =
		getServer(L)->getEmergeManager()->map_settings_mgr;

	const char *name   = luaL_checkstring(L, 1);
	const char *value  = luaL_checkstring(L, 2);
	bool override_meta = lua_isboolean(L, 3) ? lua_toboolean(L, 3) : false;

	if (!settingsmgr->setMapSetting(name, value, override_meta)) {
		errorstream << "set_mapgen_setting: cannot set '"
			<< name << "' after initialization" << std::endl;
	}

	return 0;
}

// set_mapgen_setting_noiseparams(name, noiseparams, set_default)
// set mapgen config values for noise parameters
int ModApiMapgen::l_set_mapgen_setting_noiseparams(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	MapSettingsManager *settingsmgr =
		getServer(L)->getEmergeManager()->map_settings_mgr;

	const char *name = luaL_checkstring(L, 1);

	NoiseParams np;
	if (!read_noiseparams(L, 2, &np)) {
		errorstream << "set_mapgen_setting_noiseparams: cannot set '" << name
			<< "'; invalid noiseparams table" << std::endl;
		return 0;
	}

	bool override_meta = lua_isboolean(L, 3) ? lua_toboolean(L, 3) : false;

	if (!settingsmgr->setMapSettingNoiseParams(name, &np, override_meta)) {
		errorstream << "set_mapgen_setting_noiseparams: cannot set '"
			<< name << "' after initialization" << std::endl;
	}

	return 0;
}

// set_noiseparams(name, noiseparams, set_default)
// set global config values for noise parameters
int ModApiMapgen::l_set_noiseparams(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	const char *name = luaL_checkstring(L, 1);

	NoiseParams np;
	if (!read_noiseparams(L, 2, &np)) {
		errorstream << "set_noiseparams: cannot set '" << name
			<< "'; invalid noiseparams table" << std::endl;
		return 0;
	}

	bool set_default = lua_isboolean(L, 3) ? lua_toboolean(L, 3) : true;

	g_settings->setNoiseParams(name, np, set_default);

	return 0;
}

// get_noiseparams(name)
int ModApiMapgen::l_get_noiseparams(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	std::string name = luaL_checkstring(L, 1);

	NoiseParams np;
	if (!g_settings->getNoiseParams(name, np))
		return 0;

	push_noiseparams(L, &np);
	return 1;
}

// set_gen_notify(flags, {deco_id_table})
int ModApiMapgen::l_set_gen_notify(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	u32 flags = 0, flagmask = 0;
	EmergeManager *emerge = getServer(L)->getEmergeManager();

	if (read_flags(L, 1, flagdesc_gennotify, &flags, &flagmask)) {
		emerge->gen_notify_on &= ~flagmask;
		emerge->gen_notify_on |= flags;
	}

	if (lua_istable(L, 2)) {
		lua_pushnil(L);
		while (lua_next(L, 2)) {
			if (lua_isnumber(L, -1))
				emerge->gen_notify_on_deco_ids.insert((u32)lua_tonumber(L, -1));
			lua_pop(L, 1);
		}
	}

	return 0;
}

// get_gen_notify()
int ModApiMapgen::l_get_gen_notify(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	EmergeManager *emerge = getServer(L)->getEmergeManager();
	push_flags_string(L, flagdesc_gennotify, emerge->gen_notify_on,
		emerge->gen_notify_on);

	lua_newtable(L);
	int i = 1;
	for (std::set<u32>::iterator it = emerge->gen_notify_on_deco_ids.begin();
			it != emerge->gen_notify_on_deco_ids.end(); ++it) {
		lua_pushnumber(L, *it);
		lua_rawseti(L, -2, i);
		i++;
	}
	return 2;
}

// register_biome({lots of stuff})
int ModApiMapgen::l_register_biome(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	int index = 1;
	luaL_checktype(L, index, LUA_TTABLE);

	INodeDefManager *ndef = getServer(L)->getNodeDefManager();
	BiomeManager *bmgr    = getServer(L)->getEmergeManager()->biomemgr;

	Biome *biome = read_biome_def(L, index, ndef);
	if (!biome)
		return 0;

	ObjDefHandle handle = bmgr->add(biome);
	if (handle == OBJDEF_INVALID_HANDLE) {
		delete biome;
		return 0;
	}

	lua_pushinteger(L, handle);
	return 1;
}

// register_decoration({lots of stuff})
int ModApiMapgen::l_register_decoration(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	int index = 1;
	luaL_checktype(L, index, LUA_TTABLE);

	INodeDefManager *ndef      = getServer(L)->getNodeDefManager();
	DecorationManager *decomgr = getServer(L)->getEmergeManager()->decomgr;
	BiomeManager *biomemgr     = getServer(L)->getEmergeManager()->biomemgr;
	SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;

	enum DecorationType decotype = (DecorationType)getenumfield(L, index,
				"deco_type", es_DecorationType, -1);

	Decoration *deco = decomgr->create(decotype);
	if (!deco) {
		errorstream << "register_decoration: decoration placement type "
			<< decotype << " not implemented" << std::endl;
		return 0;
	}

	deco->name       = getstringfield_default(L, index, "name", "");
	deco->fill_ratio = getfloatfield_default(L, index, "fill_ratio", 0.02);
	deco->y_min      = getintfield_default(L, index, "y_min", -31000);
	deco->y_max      = getintfield_default(L, index, "y_max", 31000);
	deco->nspawnby   = getintfield_default(L, index, "num_spawn_by", -1);
	deco->sidelen    = getintfield_default(L, index, "sidelen", 8);
	if (deco->sidelen <= 0) {
		errorstream << "register_decoration: sidelen must be "
			"greater than 0" << std::endl;
		delete deco;
		return 0;
	}

	//// Get node name(s) to place decoration on
	size_t nread = getstringlistfield(L, index, "place_on", &deco->m_nodenames);
	deco->m_nnlistsizes.push_back(nread);

	//// Get decoration flags
	getflagsfield(L, index, "flags", flagdesc_deco, &deco->flags, NULL);

	//// Get NoiseParams to define how decoration is placed
	lua_getfield(L, index, "noise_params");
	if (read_noiseparams(L, -1, &deco->np))
		deco->flags |= DECO_USE_NOISE;
	lua_pop(L, 1);

	//// Get biomes associated with this decoration (if any)
	lua_getfield(L, index, "biomes");
	if (get_biome_list(L, -1, biomemgr, &deco->biomes))
		infostream << "register_decoration: couldn't get all biomes " << std::endl;
	lua_pop(L, 1);

	//// Get node name(s) to 'spawn by'
	size_t nnames = getstringlistfield(L, index, "spawn_by", &deco->m_nodenames);
	deco->m_nnlistsizes.push_back(nnames);
	if (nnames == 0 && deco->nspawnby != -1) {
		errorstream << "register_decoration: no spawn_by nodes defined,"
			" but num_spawn_by specified" << std::endl;
	}

	//// Handle decoration type-specific parameters
	bool success = false;
	switch (decotype) {
	case DECO_SIMPLE:
		success = read_deco_simple(L, (DecoSimple *)deco);
		break;
	case DECO_SCHEMATIC:
		success = read_deco_schematic(L, schemmgr, (DecoSchematic *)deco);
		break;
	case DECO_LSYSTEM:
		break;
	}

	if (!success) {
		delete deco;
		return 0;
	}

	ndef->pendNodeResolve(deco);

	ObjDefHandle handle = decomgr->add(deco);
	if (handle == OBJDEF_INVALID_HANDLE) {
		delete deco;
		return 0;
	}

	lua_pushinteger(L, handle);
	return 1;
}

bool read_deco_simple(lua_State *L, DecoSimple *deco)
{
	int index = 1;
	int param2;

	deco->deco_height     = getintfield_default(L, index, "height", 1);
	deco->deco_height_max = getintfield_default(L, index, "height_max", 0);

	if (deco->deco_height <= 0) {
		errorstream << "register_decoration: simple decoration height"
			" must be greater than 0" << std::endl;
		return false;
	}

	size_t nnames = getstringlistfield(L, index, "decoration", &deco->m_nodenames);
	deco->m_nnlistsizes.push_back(nnames);
	if (nnames == 0) {
		errorstream << "register_decoration: no decoration nodes "
			"defined" << std::endl;
		return false;
	}

	param2 = getintfield_default(L, index, "param2", 0);
	if ((param2 < 0) || (param2 > 255)) {
		errorstream << "register_decoration: param2 out of bounds (0-255)"
			<< std::endl;
		return false;
	}
	deco->deco_param2 = (u8)param2;

	return true;
}

bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco)
{
	int index = 1;

	deco->rotation = (Rotation)getenumfield(L, index, "rotation",
		ModApiMapgen::es_Rotation, ROTATE_0);

	StringMap replace_names;
	lua_getfield(L, index, "replacements");
	if (lua_istable(L, -1))
		read_schematic_replacements(L, -1, &replace_names);
	lua_pop(L, 1);

	lua_getfield(L, index, "schematic");
	Schematic *schem = get_or_load_schematic(L, -1, schemmgr, &replace_names);
	lua_pop(L, 1);

	deco->schematic = schem;
	return schem != NULL;
}

// register_ore({lots of stuff})
int ModApiMapgen::l_register_ore(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	int index = 1;
	luaL_checktype(L, index, LUA_TTABLE);

	INodeDefManager *ndef = getServer(L)->getNodeDefManager();
	BiomeManager *bmgr    = getServer(L)->getEmergeManager()->biomemgr;
	OreManager *oremgr    = getServer(L)->getEmergeManager()->oremgr;

	enum OreType oretype = (OreType)getenumfield(L, index,
				"ore_type", es_OreType, ORE_SCATTER);
	Ore *ore = oremgr->create(oretype);
	if (!ore) {
		errorstream << "register_ore: ore_type " << oretype << " not implemented\n";
		return 0;
	}

	ore->name           = getstringfield_default(L, index, "name", "");
	ore->ore_param2     = (u8)getintfield_default(L, index, "ore_param2", 0);
	ore->clust_scarcity = getintfield_default(L, index, "clust_scarcity", 1);
	ore->clust_num_ores = getintfield_default(L, index, "clust_num_ores", 1);
	ore->clust_size     = getintfield_default(L, index, "clust_size", 0);
	ore->noise          = NULL;
	ore->flags          = 0;

	//// Get noise_threshold
	warn_if_field_exists(L, index, "noise_threshhold",
		"Deprecated: new name is \"noise_threshold\".");

	float nthresh;
	if (!getfloatfield(L, index, "noise_threshold", nthresh) &&
			!getfloatfield(L, index, "noise_threshhold", nthresh))
		nthresh = 0;
	ore->nthresh = nthresh;

	//// Get y_min/y_max
	warn_if_field_exists(L, index, "height_min",
		"Deprecated: new name is \"y_min\".");
	warn_if_field_exists(L, index, "height_max",
		"Deprecated: new name is \"y_max\".");

	int ymin, ymax;
	if (!getintfield(L, index, "y_min", ymin) &&
		!getintfield(L, index, "height_min", ymin))
		ymin = -31000;
	if (!getintfield(L, index, "y_max", ymax) &&
		!getintfield(L, index, "height_max", ymax))
		ymax = 31000;
	ore->y_min = ymin;
	ore->y_max = ymax;

	if (ore->clust_scarcity <= 0 || ore->clust_num_ores <= 0) {
		errorstream << "register_ore: clust_scarcity and clust_num_ores"
			"must be greater than 0" << std::endl;
		delete ore;
		return 0;
	}

	//// Get flags
	getflagsfield(L, index, "flags", flagdesc_ore, &ore->flags, NULL);

	//// Get biomes associated with this decoration (if any)
	lua_getfield(L, index, "biomes");
	if (get_biome_list(L, -1, bmgr, &ore->biomes))
		infostream << "register_ore: couldn't get all biomes " << std::endl;
	lua_pop(L, 1);

	//// Get noise parameters if needed
	lua_getfield(L, index, "noise_params");
	if (read_noiseparams(L, -1, &ore->np)) {
		ore->flags |= OREFLAG_USE_NOISE;
	} else if (ore->NEEDS_NOISE) {
		errorstream << "register_ore: specified ore type requires valid "
			"noise parameters" << std::endl;
		delete ore;
		return 0;
	}
	lua_pop(L, 1);

	//// Get type-specific parameters
	switch (oretype) {
		case ORE_SHEET: {
			OreSheet *oresheet = (OreSheet *)ore;

			oresheet->column_height_min = getintfield_default(L, index,
				"column_height_min", 1);
			oresheet->column_height_max = getintfield_default(L, index,
				"column_height_max", ore->clust_size);
			oresheet->column_midpoint_factor = getfloatfield_default(L, index,
				"column_midpoint_factor", 0.5f);

			break;
		}
		case ORE_PUFF: {
			OrePuff *orepuff = (OrePuff *)ore;

			lua_getfield(L, index, "np_puff_top");
			read_noiseparams(L, -1, &orepuff->np_puff_top);
			lua_pop(L, 1);

			lua_getfield(L, index, "np_puff_bottom");
			read_noiseparams(L, -1, &orepuff->np_puff_bottom);
			lua_pop(L, 1);

			break;
		}
		case ORE_VEIN: {
			OreVein *orevein = (OreVein *)ore;

			orevein->random_factor = getfloatfield_default(L, index,
				"random_factor", 1.f);

			break;
		}
		default:
			break;
	}

	ObjDefHandle handle = oremgr->add(ore);
	if (handle == OBJDEF_INVALID_HANDLE) {
		delete ore;
		return 0;
	}

	ore->m_nodenames.push_back(getstringfield_default(L, index, "ore", ""));

	size_t nnames = getstringlistfield(L, index, "wherein", &ore->m_nodenames);
	ore->m_nnlistsizes.push_back(nnames);

	ndef->pendNodeResolve(ore);

	lua_pushinteger(L, handle);
	return 1;
}

// register_schematic({schematic}, replacements={})
int ModApiMapgen::l_register_schematic(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;

	StringMap replace_names;
	if (lua_istable(L, 2))
		read_schematic_replacements(L, 2, &replace_names);

	Schematic *schem = load_schematic(L, 1, schemmgr->getNodeDef(),
		&replace_names);
	if (!schem)
		return 0;

	ObjDefHandle handle = schemmgr->add(schem);
	if (handle == OBJDEF_INVALID_HANDLE) {
		delete schem;
		return 0;
	}

	lua_pushinteger(L, handle);
	return 1;
}

// clear_registered_biomes()
int ModApiMapgen::l_clear_registered_biomes(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr;
	bmgr->clear();
	return 0;
}

// clear_registered_decorations()
int ModApiMapgen::l_clear_registered_decorations(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	DecorationManager *dmgr = getServer(L)->getEmergeManager()->decomgr;
	dmgr->clear();
	return 0;
}

// clear_registered_ores()
int ModApiMapgen::l_clear_registered_ores(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	OreManager *omgr = getServer(L)->getEmergeManager()->oremgr;
	omgr->clear();
	return 0;
}

// clear_registered_schematics()
int ModApiMapgen::l_clear_registered_schematics(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	SchematicManager *smgr = getServer(L)->getEmergeManager()->schemmgr;
	smgr->clear();
	return 0;
}

// generate_ores(vm, p1, p2, [ore_id])
int ModApiMapgen::l_generate_ores(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	EmergeManager *emerge = getServer(L)->getEmergeManager();

	Mapgen mg;
	mg.seed = emerge->mgparams->seed;
	mg.vm   = LuaVoxelManip::checkobject(L, 1)->vm;
	mg.ndef = getServer(L)->getNodeDefManager();

	v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) :
			mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE;
	v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) :
			mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE;
	sortBoxVerticies(pmin, pmax);

	u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed);

	emerge->oremgr->placeAllOres(&mg, blockseed, pmin, pmax);

	return 0;
}

// generate_decorations(vm, p1, p2, [deco_id])
int ModApiMapgen::l_generate_decorations(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	EmergeManager *emerge = getServer(L)->getEmergeManager();

	Mapgen mg;
	mg.seed = emerge->mgparams->seed;
	mg.vm   = LuaVoxelManip::checkobject(L, 1)->vm;
	mg.ndef = getServer(L)->getNodeDefManager();

	v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) :
			mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE;
	v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) :
			mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE;
	sortBoxVerticies(pmin, pmax);

	u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed);

	emerge->decomgr->placeAllDecos(&mg, blockseed, pmin, pmax);

	return 0;
}

// create_schematic(p1, p2, probability_list, filename, y_slice_prob_list)
int ModApiMapgen::l_create_schematic(lua_State *L)
{
	MAP_LOCK_REQUIRED;

	INodeDefManager *ndef = getServer(L)->getNodeDefManager();

	const char *filename = luaL_checkstring(L, 4);
	CHECK_SECURE_PATH(L, filename, true);

	Map *map = &(getEnv(L)->getMap());
	Schematic schem;

	v3s16 p1 = check_v3s16(L, 1);
	v3s16 p2 = check_v3s16(L, 2);
	sortBoxVerticies(p1, p2);

	std::vector<std::pair<v3s16, u8> > prob_list;
	if (lua_istable(L, 3)) {
		lua_pushnil(L);
		while (lua_next(L, 3)) {
			if (lua_istable(L, -1)) {
				lua_getfield(L, -1, "pos");
				v3s16 pos = check_v3s16(L, -1);
				lua_pop(L, 1);

				u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS);
				prob_list.push_back(std::make_pair(pos, prob));
			}

			lua_pop(L, 1);
		}
	}

	std::vector<std::pair<s16, u8> > slice_prob_list;
	if (lua_istable(L, 5)) {
		lua_pushnil(L);
		while (lua_next(L, 5)) {
			if (lua_istable(L, -1)) {
				s16 ypos = getintfield_default(L, -1, "ypos", 0);
				u8 prob  = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS);
				slice_prob_list.push_back(std::make_pair(ypos, prob));
			}

			lua_pop(L, 1);
		}
	}

	if (!schem.getSchematicFromMap(map, p1, p2)) {
		errorstream << "create_schematic: failed to get schematic "
			"from map" << std::endl;
		return 0;
	}

	schem.applyProbabilities(p1, &prob_list, &slice_prob_list);

	schem.saveSchematicToFile(filename, ndef);
	actionstream << "create_schematic: saved schematic file '"
		<< filename << "'." << std::endl;

	lua_pushboolean(L, true);
	return 1;
}

// place_schematic(p, schematic, rotation, replacement)
int ModApiMapgen::l_place_schematic(lua_State *L)
{
	MAP_LOCK_REQUIRED;

	GET_ENV_PTR;

	ServerMap *map = &(env->getServerMap());
	SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;

	//// Read position
	v3s16 p = check_v3s16(L, 1);

	//// Read rotation
	int rot = ROTATE_0;
	const char *enumstr = lua_tostring(L, 3);
	if (enumstr)
		string_to_enum(es_Rotation, rot, std::string(enumstr));

	//// Read force placement
	bool force_placement = true;
	if (lua_isboolean(L, 5))
		force_placement = lua_toboolean(L, 5);

	//// Read node replacements
	StringMap replace_names;
	if (lua_istable(L, 4))
		read_schematic_replacements(L, 4, &replace_names);

	//// Read schematic
	Schematic *schem = get_or_load_schematic(L, 2, schemmgr, &replace_names);
	if (!schem) {
		errorstream << "place_schematic: failed to get schematic" << std::endl;
		return 0;
	}

	schem->placeOnMap(map, p, 0, (Rotation)rot, force_placement);

	lua_pushboolean(L, true);
	return 1;
}

int ModApiMapgen::l_place_schematic_on_vmanip(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;

	//// Read VoxelManip object
	MMVManip *vm = LuaVoxelManip::checkobject(L, 1)->vm;

	//// Read position
	v3s16 p = check_v3s16(L, 2);

	//// Read rotation
	int rot = ROTATE_0;
	const char *enumstr = lua_tostring(L, 4);
	if (enumstr)
		string_to_enum(es_Rotation, rot, std::string(enumstr));

	//// Read force placement
	bool force_placement = true;
	if (lua_isboolean(L, 6))
		force_placement = lua_toboolean(L, 6);

	//// Read node replacements
	StringMap replace_names;
	if (lua_istable(L, 5))
		read_schematic_replacements(L, 5, &replace_names);

	//// Read schematic
	Schematic *schem = get_or_load_schematic(L, 3, schemmgr, &replace_names);
	if (!schem) {
		errorstream << "place_schematic: failed to get schematic" << std::endl;
		return 0;
	}

	bool schematic_did_fit = schem->placeOnVManip(
		vm, p, 0, (Rotation)rot, force_placement);

	lua_pushboolean(L, schematic_did_fit);
	return 1;
}

// serialize_schematic(schematic, format, options={...})
int ModApiMapgen::l_serialize_schematic(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;

	//// Read options
	bool use_comments = getboolfield_default(L, 3, "lua_use_comments", false);
	u32 indent_spaces = getintfield_default(L, 3, "lua_num_indent_spaces", 0);

	//// Get schematic
	bool was_loaded = false;
	Schematic *schem = (Schematic *)get_objdef(L, 1, schemmgr);
	if (!schem) {
		schem = load_schematic(L, 1, NULL, NULL);
		was_loaded = true;
	}
	if (!schem) {
		errorstream << "serialize_schematic: failed to get schematic" << std::endl;
		return 0;
	}

	//// Read format of definition to save as
	int schem_format = SCHEM_FMT_MTS;
	const char *enumstr = lua_tostring(L, 2);
	if (enumstr)
		string_to_enum(es_SchematicFormatType, schem_format, std::string(enumstr));

	//// Serialize to binary string
	std::ostringstream os(std::ios_base::binary);
	switch (schem_format) {
	case SCHEM_FMT_MTS:
		schem->serializeToMts(&os, schem->m_nodenames);
		break;
	case SCHEM_FMT_LUA:
		schem->serializeToLua(&os, schem->m_nodenames,
			use_comments, indent_spaces);
		break;
	default:
		return 0;
	}

	if (was_loaded)
		delete schem;

	std::string ser = os.str();
	lua_pushlstring(L, ser.c_str(), ser.length());
	return 1;
}

void ModApiMapgen::Initialize(lua_State *L, int top)
{
	API_FCT(get_biome_id);
	API_FCT(get_mapgen_object);

	API_FCT(get_mapgen_params);
	API_FCT(set_mapgen_params);
	API_FCT(get_mapgen_setting);
	API_FCT(set_mapgen_setting);
	API_FCT(get_mapgen_setting_noiseparams);
	API_FCT(set_mapgen_setting_noiseparams);
	API_FCT(set_noiseparams);
	API_FCT(get_noiseparams);
	API_FCT(set_gen_notify);
	API_FCT(get_gen_notify);

	API_FCT(register_biome);
	API_FCT(register_decoration);
	API_FCT(register_ore);
	API_FCT(register_schematic);

	API_FCT(clear_registered_biomes);
	API_FCT(clear_registered_decorations);
	API_FCT(clear_registered_ores);
	API_FCT(clear_registered_schematics);

	API_FCT(generate_ores);
	API_FCT(generate_decorations);
	API_FCT(create_schematic);
	API_FCT(place_schematic);
	API_FCT(place_schematic_on_vmanip);
	API_FCT(serialize_schematic);
}


code:
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#ifndef L_MAPGEN_H_
#define L_MAPGEN_H_

#include "lua_api/l_base.h"

class ModApiMapgen : public ModApiBase
{
private:
	// get_biome_id(biomename)
	// returns the biome id used in biomemap
	static int l_get_biome_id(lua_State *L);

	// get_mapgen_object(objectname)
	// returns the requested object used during map generation
	static int l_get_mapgen_object(lua_State *L);

	// get_mapgen_params()
	// returns the currently active map generation parameter set
	static int l_get_mapgen_params(lua_State *L);

	// set_mapgen_params(params)
	// set mapgen parameters
	static int l_set_mapgen_params(lua_State *L);

	// get_mapgen_setting(name)
	static int l_get_mapgen_setting(lua_State *L);

	// set_mapgen_setting(name, value, override_meta)
	static int l_set_mapgen_setting(lua_State *L);

	// get_mapgen_setting_noiseparams(name)
	static int l_get_mapgen_setting_noiseparams(lua_State *L);

	// set_mapgen_setting_noiseparams(name, value, override_meta)
	static int l_set_mapgen_setting_noiseparams(lua_State *L);

	// set_noiseparam_defaults(name, noiseparams, set_default)
	static int l_set_noiseparams(lua_State *L);

	// get_noiseparam_defaults(name)
	static int l_get_noiseparams(lua_State *L);

	// set_gen_notify(flagstring)
	static int l_set_gen_notify(lua_State *L);

	// set_gen_notify(flagstring)
	static int l_get_gen_notify(lua_State *L);

	// register_biome({lots of stuff})
	static int l_register_biome(lua_State *L);

	// register_decoration({lots of stuff})
	static int l_register_decoration(lua_State *L);

	// register_ore({lots of stuff})
	static int l_register_ore(lua_State *L);

	// register_schematic({schematic}, replacements={})
	static int l_register_schematic(lua_State *L);

	// clear_registered_biomes()
	static int l_clear_registered_biomes(lua_State *L);

	// clear_registered_decorations()
	static int l_clear_registered_decorations(lua_State *L);

	// clear_registered_schematics()
	static int l_clear_registered_schematics(lua_State *L);

	// generate_ores(vm, p1, p2)
	static int l_generate_ores(lua_State *L);

	// generate_decorations(vm, p1, p2)
	static int l_generate_decorations(lua_State *L);

	// clear_registered_ores
	static int l_clear_registered_ores(lua_State *L);

	// create_schematic(p1, p2, probability_list, filename)
	static int l_create_schematic(lua_State *L);

	// place_schematic(p, schematic, rotation, replacements, force_placement)
	static int l_place_schematic(lua_State *L);

	// place_schematic_on_vmanip(vm, p, schematic,
	//     rotation, replacements, force_placement)
	static int l_place_schematic_on_vmanip(lua_State *L);

	// serialize_schematic(schematic, format, options={...})
	static int l_serialize_schematic(lua_State *L);

public:
	static void Initialize(lua_State *L, int top);

	static struct EnumString es_BiomeTerrainType[];
	static struct EnumString es_DecorationType[];
	static struct EnumString es_MapgenObject[];
	static struct EnumString es_OreType[];
	static struct EnumString es_Rotation[];
	static struct EnumString es_SchematicFormatType[];
	static struct EnumString es_NodeResolveMethod[];
};

#endif /* L_MAPGEN_H_ */


code:
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "lua_api/l_metadata.h"
#include "lua_api/l_internal.h"
#include "common/c_content.h"
#include "serverenvironment.h"
#include "map.h"
#include "server.h"

// LUALIB_API
void *luaL_checkudata_is_metadataref(lua_State *L, int ud) {
	void *p = lua_touserdata(L, ud);
	if (p != NULL &&  // value is a userdata?
			lua_getmetatable(L, ud)) {  // does it have a metatable?
		lua_getfield(L, -1, "metadata_class");
		if (lua_type(L, -1) == LUA_TSTRING) { // does it have a metadata_class field?
			return p;
		}
	}
	luaL_typerror(L, ud, "MetaDataRef");
	return NULL;
}

MetaDataRef* MetaDataRef::checkobject(lua_State *L, int narg)
{
	luaL_checktype(L, narg, LUA_TUSERDATA);
	void *ud = luaL_checkudata_is_metadataref(L, narg);
	if (!ud)
		luaL_typerror(L, narg, "MetaDataRef");

	return *(MetaDataRef**)ud;  // unbox pointer
}

// Exported functions

// get_string(self, name)
int MetaDataRef::l_get_string(lua_State *L)
{
	MAP_LOCK_REQUIRED;

	MetaDataRef *ref = checkobject(L, 1);
	std::string name = luaL_checkstring(L, 2);

	Metadata *meta = ref->getmeta(false);
	if (meta == NULL) {
		lua_pushlstring(L, "", 0);
		return 1;
	}

	const std::string &str = meta->getString(name);
	lua_pushlstring(L, str.c_str(), str.size());
	return 1;
}

// set_string(self, name, var)
int MetaDataRef::l_set_string(lua_State *L)
{
	MAP_LOCK_REQUIRED;

	MetaDataRef *ref = checkobject(L, 1);
	std::string name = luaL_checkstring(L, 2);
	size_t len = 0;
	const char *s = lua_tolstring(L, 3, &len);
	std::string str(s, len);

	Metadata *meta = ref->getmeta(!str.empty());
	if (meta == NULL || str == meta->getString(name))
		return 0;

	meta->setString(name, str);
	ref->reportMetadataChange();
	return 0;
}

// get_int(self, name)
int MetaDataRef::l_get_int(lua_State *L)
{
	MAP_LOCK_REQUIRED;

	MetaDataRef *ref = checkobject(L, 1);
	std::string name = lua_tostring(L, 2);

	Metadata *meta = ref->getmeta(false);
	if (meta == NULL) {
		lua_pushnumber(L, 0);
		return 1;
	}

	const std::string &str = meta->getString(name);
	lua_pushnumber(L, stoi(str));
	return 1;
}

// set_int(self, name, var)
int MetaDataRef::l_set_int(lua_State *L)
{
	MAP_LOCK_REQUIRED;

	MetaDataRef *ref = checkobject(L, 1);
	std::string name = lua_tostring(L, 2);
	int a = lua_tointeger(L, 3);
	std::string str = itos(a);

	Metadata *meta = ref->getmeta(true);
	if (meta == NULL || str == meta->getString(name))
		return 0;

	meta->setString(name, str);
	ref->reportMetadataChange();
	return 0;
}

// get_float(self, name)
int MetaDataRef::l_get_float(lua_State *L)
{
	MAP_LOCK_REQUIRED;

	MetaDataRef *ref = checkobject(L, 1);
	std::string name = lua_tostring(L, 2);

	Metadata *meta = ref->getmeta(false);
	if (meta == NULL) {
		lua_pushnumber(L, 0);
		return 1;
	}

	const std::string &str = meta->getString(name);
	lua_pushnumber(L, stof(str));
	return 1;
}

// set_float(self, name, var)
int MetaDataRef::l_set_float(lua_State *L)
{
	MAP_LOCK_REQUIRED;

	MetaDataRef *ref = checkobject(L, 1);
	std::string name = lua_tostring(L, 2);
	float a = lua_tonumber(L, 3);
	std::string str = ftos(a);

	Metadata *meta = ref->getmeta(true);
	if (meta == NULL || str == meta->getString(name))
		return 0;

	meta->setString(name, str);
	ref->reportMetadataChange();
	return 0;
}

// to_table(self)
int MetaDataRef::l_to_table(lua_State *L)
{
	MAP_LOCK_REQUIRED;

	MetaDataRef *ref = checkobject(L, 1);

	Metadata *meta = ref->getmeta(true);
	if (meta == NULL) {
		lua_pushnil(L);
		return 1;
	}
	lua_newtable(L);

	ref->handleToTable(L, meta);

	return 1;
}

// from_table(self, table)
int MetaDataRef::l_from_table(lua_State *L)
{
	MAP_LOCK_REQUIRED;

	MetaDataRef *ref = checkobject(L, 1);
	int base = 2;

	ref->clearMeta();

	if (!lua_istable(L, base)) {
		// No metadata
		lua_pushboolean(L, true);
		return 1;
	}

	// Create new metadata
	Metadata *meta = ref->getmeta(true);
	if (meta == NULL) {
		lua_pushboolean(L, false);
		return 1;
	}

	bool was_successful = ref->handleFromTable(L, base, meta);
	ref->reportMetadataChange();
	lua_pushboolean(L, was_successful);
	return 1;
}

void MetaDataRef::handleToTable(lua_State *L, Metadata *meta)
{
	lua_newtable(L);
	{
		const StringMap &fields = meta->getStrings();
		for (StringMap::const_iterator
				it = fields.begin(); it != fields.end(); ++it) {
			const std::string &name = it->first;
			const std::string &value = it->second;
			lua_pushlstring(L, name.c_str(), name.size());
			lua_pushlstring(L, value.c_str(), value.size());
			lua_settable(L, -3);
		}
	}
	lua_setfield(L, -2, "fields");
}

bool MetaDataRef::handleFromTable(lua_State *L, int table, Metadata *meta)
{
	// Set fields
	lua_getfield(L, table, "fields");
	if (lua_istable(L, -1)) {
		int fieldstable = lua_gettop(L);
		lua_pushnil(L);
		while (lua_next(L, fieldstable) != 0) {
			// key at index -2 and value at index -1
			std::string name = lua_tostring(L, -2);
			size_t cl;
			const char *cs = lua_tolstring(L, -1, &cl);
			meta->setString(name, std::string(cs, cl));
			lua_pop(L, 1); // Remove value, keep key for next iteration
		}
		lua_pop(L, 1);
	}

	return true;
}

// equals(self, other)
int MetaDataRef::l_equals(lua_State *L)
{
	MetaDataRef *ref1 = checkobject(L, 1);
	Metadata *data1 = ref1->getmeta(false);
	MetaDataRef *ref2 = checkobject(L, 2);
	Metadata *data2 = ref2->getmeta(false);
	if (data1 == NULL || data2 == NULL)
		lua_pushboolean(L, data1 == data2);
	else
		lua_pushboolean(L, *data1 == *data2);
	return 1;
}


code:
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef L_METADATA_H_
#define L_METADATA_H_

#include "irrlichttypes_bloated.h"
#include "lua_api/l_base.h"

class Metadata;

/*
	NodeMetaRef
*/

class MetaDataRef : public ModApiBase
{
public:
	virtual ~MetaDataRef() {}
protected:
	static MetaDataRef *checkobject(lua_State *L, int narg);

	virtual void reportMetadataChange() {}
	virtual Metadata *getmeta(bool auto_create) = 0;
	virtual void clearMeta() = 0;

	virtual void handleToTable(lua_State *L, Metadata *meta);
	virtual bool handleFromTable(lua_State *L, int table, Metadata *meta);

	// Exported functions

	// get_string(self, name)
	static int l_get_string(lua_State *L);

	// set_string(self, name, var)
	static int l_set_string(lua_State *L);

	// get_int(self, name)
	static int l_get_int(lua_State *L);

	// set_int(self, name, var)
	static int l_set_int(lua_State *L);

	// get_float(self, name)
	static int l_get_float(lua_State *L);

	// set_float(self, name, var)
	static int l_set_float(lua_State *L);

	// to_table(self)
	static int l_to_table(lua_State *L);

	// from_table(self, table)
	static int l_from_table(lua_State *L);

	// equals(self, other)
	static int l_equals(lua_State *L);
};

#endif /* L_NODEMETA_H_ */


code:
/*
Minetest
Copyright (C) 2017 Loic Blot <loic.blot@unix-experience.fr>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "lua_api/l_minimap.h"
#include "lua_api/l_internal.h"
#include "common/c_converter.h"
#include "minimap.h"
#include "settings.h"

LuaMinimap::LuaMinimap(Minimap *m)
{
	m_minimap = m;
}

void LuaMinimap::create(lua_State *L, Minimap *m)
{
	LuaMinimap *o = new LuaMinimap(m);
	*(void **)(lua_newuserdata(L, sizeof(void *))) = o;
	luaL_getmetatable(L, className);
	lua_setmetatable(L, -2);

	// Keep minimap object stack id
	int minimap_object = lua_gettop(L);

	lua_getglobal(L, "core");
	lua_getfield(L, -1, "ui");
	luaL_checktype(L, -1, LUA_TTABLE);
	int uitable = lua_gettop(L);

	lua_pushvalue(L, minimap_object); // Copy object to top of stack
	lua_setfield(L, uitable, "minimap");
}

int LuaMinimap::l_get_pos(lua_State *L)
{
	LuaMinimap *ref = checkobject(L, 1);
	Minimap *m = getobject(ref);

	push_v3s16(L, m->getPos());
	return 1;
}

int LuaMinimap::l_set_pos(lua_State *L)
{
	LuaMinimap *ref = checkobject(L, 1);
	Minimap *m = getobject(ref);

	m->setPos(read_v3s16(L, 2));
	return 1;
}

int LuaMinimap::l_get_angle(lua_State *L)
{
	LuaMinimap *ref = checkobject(L, 1);
	Minimap *m = getobject(ref);

	lua_pushinteger(L, m->getAngle());
	return 1;
}

int LuaMinimap::l_set_angle(lua_State *L)
{
	LuaMinimap *ref = checkobject(L, 1);
	Minimap *m = getobject(ref);

	m->setAngle(lua_tointeger(L, 2));
	return 1;
}

int LuaMinimap::l_get_mode(lua_State *L)
{
	LuaMinimap *ref = checkobject(L, 1);
	Minimap *m = getobject(ref);

	lua_pushinteger(L, m->getMinimapMode());
	return 1;
}

int LuaMinimap::l_set_mode(lua_State *L)
{
	LuaMinimap *ref = checkobject(L, 1);
	Minimap *m = getobject(ref);

	s32 mode = lua_tointeger(L, 2);
	if (mode < MINIMAP_MODE_OFF ||
		mode >= MINIMAP_MODE_COUNT) {
		return 0;
	}

	m->setMinimapMode((MinimapMode) mode);
	return 1;
}

int LuaMinimap::l_set_shape(lua_State *L)
{
	LuaMinimap *ref = checkobject(L, 1);
	Minimap *m = getobject(ref);
	if (!lua_isnumber(L, 2))
		return 0;

	m->setMinimapShape((MinimapShape)((int)lua_tonumber(L, 2)));
	return 0;
}

int LuaMinimap::l_get_shape(lua_State *L)
{
	LuaMinimap *ref = checkobject(L, 1);
	Minimap *m = getobject(ref);

	lua_pushnumber(L, (int)m->getMinimapShape());
	return 1;
}

int LuaMinimap::l_show(lua_State *L)
{
	// If minimap is disabled by config, don't show it.
	if (!g_settings->getBool("enable_minimap"))
		return 1;

	Client *client = getClient(L);
	assert(client);

	LuaMinimap *ref = checkobject(L, 1);
	Minimap *m = getobject(ref);

	if (m->getMinimapMode() == MINIMAP_MODE_OFF)
		m->setMinimapMode(MINIMAP_MODE_SURFACEx1);

	client->showMinimap(true);
	return 1;
}

int LuaMinimap::l_hide(lua_State *L)
{
	Client *client = getClient(L);
	assert(client);

	LuaMinimap *ref = checkobject(L, 1);
	Minimap *m = getobject(ref);

	if (m->getMinimapMode() != MINIMAP_MODE_OFF)
		m->setMinimapMode(MINIMAP_MODE_OFF);

	client->showMinimap(false);
	return 1;
}

LuaMinimap *LuaMinimap::checkobject(lua_State *L, int narg)
{
	NO_MAP_LOCK_REQUIRED;

	luaL_checktype(L, narg, LUA_TUSERDATA);

	void *ud = luaL_checkudata(L, narg, className);
	if (!ud)
		luaL_typerror(L, narg, className);

	return *(LuaMinimap **)ud;  // unbox pointer
}

Minimap* LuaMinimap::getobject(LuaMinimap *ref)
{
	return ref->m_minimap;
}

int LuaMinimap::gc_object(lua_State *L) {
	LuaMinimap *o = *(LuaMinimap **)(lua_touserdata(L, 1));
	delete o;
	return 0;
}

void LuaMinimap::Register(lua_State *L)
{
	lua_newtable(L);
	int methodtable = lua_gettop(L);
	luaL_newmetatable(L, className);
	int metatable = lua_gettop(L);

	lua_pushliteral(L, "__metatable");
	lua_pushvalue(L, methodtable);
	lua_settable(L, metatable);  // hide metatable from Lua getmetatable()

	lua_pushliteral(L, "__index");
	lua_pushvalue(L, methodtable);
	lua_settable(L, metatable);

	lua_pushliteral(L, "__gc");
	lua_pushcfunction(L, gc_object);
	lua_settable(L, metatable);

	lua_pop(L, 1);  // drop metatable

	luaL_openlib(L, 0, methods, 0);  // fill methodtable
	lua_pop(L, 1);  // drop methodtable
}

const char LuaMinimap::className[] = "Minimap";
const luaL_Reg LuaMinimap::methods[] = {
	luamethod(LuaMinimap, show),
	luamethod(LuaMinimap, hide),
	luamethod(LuaMinimap, get_pos),
	luamethod(LuaMinimap, set_pos),
	luamethod(LuaMinimap, get_angle),
	luamethod(LuaMinimap, set_angle),
	luamethod(LuaMinimap, get_mode),
	luamethod(LuaMinimap, set_mode),
	luamethod(LuaMinimap, set_shape),
	luamethod(LuaMinimap, get_shape),
	{0,0}
};


code:
/*
Minetest
Copyright (C) 2017 Loic Blot <loic.blot@unix-experience.fr>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#ifndef L_MINIMAP_H_
#define L_MINIMAP_H_

#include "l_base.h"

class Minimap;

class LuaMinimap : public ModApiBase
{
private:
	static const char className[];
	static const luaL_Reg methods[];

	// garbage collector
	static int gc_object(lua_State *L);

	static int l_get_pos(lua_State *L);
	static int l_set_pos(lua_State *L);

	static int l_get_angle(lua_State *L);
	static int l_set_angle(lua_State *L);

	static int l_get_mode(lua_State *L);
	static int l_set_mode(lua_State *L);

	static int l_show(lua_State *L);
	static int l_hide(lua_State *L);

	static int l_set_shape(lua_State *L);
	static int l_get_shape(lua_State *L);

	Minimap *m_minimap;

public:
	LuaMinimap(Minimap *m);
	~LuaMinimap() {}

	static void create(lua_State *L, Minimap *object);

	static LuaMinimap *checkobject(lua_State *L, int narg);
	static Minimap *getobject(LuaMinimap *ref);

	static void Register(lua_State *L);
};

#endif // L_MINIMAP_H_