+ if(!lua_istable(L, index))
+ return false;
+
+ lua_pushnil(L);
+ while(lua_next(L, index) != 0){
+ // key at index -2 and value at index -1
+ if(!lua_istable(L, -1))
+ return false;
+ lua_rawgeti(L, -1, 1);
+ if(!lua_isstring(L, -1))
+ return false;
+ std::string replace_from = lua_tostring(L, -1);
+ lua_pop(L, 1);
+ lua_rawgeti(L, -1, 2);
+ if(!lua_isstring(L, -1))
+ return false;
+ std::string replace_to = lua_tostring(L, -1);
+ lua_pop(L, 1);
+ replacements.pairs.push_back(
+ std::make_pair(replace_from, replace_to));
+ // removes value, keeps key for next iteration
+ lua_pop(L, 1);
+ }
+ return true;
+}
+// register_craft({output=item, recipe={{item00,item10},{item01,item11}})
+static int l_register_craft(lua_State *L)
+{
+ //infostream<<"register_craft"<<std::endl;
+ luaL_checktype(L, 1, LUA_TTABLE);
+ int table = 1;
+
+ // Get the writable craft definition manager from the server
+ IWritableCraftDefManager *craftdef =
+ get_server(L)->getWritableCraftDefManager();
+
+ std::string type = getstringfield_default(L, table, "type", "shaped");
+
+ /*
+ CraftDefinitionShaped
+ */
+ if(type == "shaped"){
+ std::string output = getstringfield_default(L, table, "output", "");
+ if(output == "")
+ throw LuaError(L, "Crafting definition is missing an output");
+
+ int width = 0;
+ std::vector<std::string> recipe;
+ lua_getfield(L, table, "recipe");
+ if(lua_isnil(L, -1))
+ throw LuaError(L, "Crafting definition is missing a recipe"
+ " (output=\"" + output + "\")");
+ if(!read_craft_recipe_shaped(L, -1, width, recipe))
+ throw LuaError(L, "Invalid crafting recipe"
+ " (output=\"" + output + "\")");
+
+ CraftReplacements replacements;
+ lua_getfield(L, table, "replacements");
+ if(!lua_isnil(L, -1))
+ {
+ if(!read_craft_replacements(L, -1, replacements))
+ throw LuaError(L, "Invalid replacements"
+ " (output=\"" + output + "\")");
+ }
+
+ CraftDefinition *def = new CraftDefinitionShaped(
+ output, width, recipe, replacements);
+ craftdef->registerCraft(def);
+ }
+ /*
+ CraftDefinitionShapeless
+ */
+ else if(type == "shapeless"){
+ std::string output = getstringfield_default(L, table, "output", "");
+ if(output == "")
+ throw LuaError(L, "Crafting definition (shapeless)"
+ " is missing an output");
+
+ std::vector<std::string> recipe;
+ lua_getfield(L, table, "recipe");
+ if(lua_isnil(L, -1))
+ throw LuaError(L, "Crafting definition (shapeless)"
+ " is missing a recipe"
+ " (output=\"" + output + "\")");
+ if(!read_craft_recipe_shapeless(L, -1, recipe))
+ throw LuaError(L, "Invalid crafting recipe"
+ " (output=\"" + output + "\")");
+
+ CraftReplacements replacements;
+ lua_getfield(L, table, "replacements");
+ if(!lua_isnil(L, -1))
+ {
+ if(!read_craft_replacements(L, -1, replacements))
+ throw LuaError(L, "Invalid replacements"
+ " (output=\"" + output + "\")");
+ }
+
+ CraftDefinition *def = new CraftDefinitionShapeless(
+ output, recipe, replacements);
+ craftdef->registerCraft(def);
+ }
+ /*
+ CraftDefinitionToolRepair
+ */
+ else if(type == "toolrepair"){
+ float additional_wear = getfloatfield_default(L, table,
+ "additional_wear", 0.0);
+
+ CraftDefinition *def = new CraftDefinitionToolRepair(
+ additional_wear);
+ craftdef->registerCraft(def);
+ }
+ /*
+ CraftDefinitionCooking
+ */
+ else if(type == "cooking"){
+ std::string output = getstringfield_default(L, table, "output", "");
+ if(output == "")
+ throw LuaError(L, "Crafting definition (cooking)"
+ " is missing an output");
+
+ std::string recipe = getstringfield_default(L, table, "recipe", "");
+ if(recipe == "")
+ throw LuaError(L, "Crafting definition (cooking)"
+ " is missing a recipe"
+ " (output=\"" + output + "\")");
+
+ float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
+
+ CraftReplacements replacements;
+ lua_getfield(L, table, "replacements");
+ if(!lua_isnil(L, -1))
+ {
+ if(!read_craft_replacements(L, -1, replacements))
+ throw LuaError(L, "Invalid replacements"
+ " (cooking output=\"" + output + "\")");
+ }
+
+ CraftDefinition *def = new CraftDefinitionCooking(
+ output, recipe, cooktime, replacements);
+ craftdef->registerCraft(def);
+ }
+ /*
+ CraftDefinitionFuel
+ */
+ else if(type == "fuel"){
+ std::string recipe = getstringfield_default(L, table, "recipe", "");
+ if(recipe == "")
+ throw LuaError(L, "Crafting definition (fuel)"
+ " is missing a recipe");
+
+ float burntime = getfloatfield_default(L, table, "burntime", 1.0);
+
+ CraftReplacements replacements;
+ lua_getfield(L, table, "replacements");
+ if(!lua_isnil(L, -1))
+ {
+ if(!read_craft_replacements(L, -1, replacements))
+ throw LuaError(L, "Invalid replacements"
+ " (fuel recipe=\"" + recipe + "\")");
+ }
+
+ CraftDefinition *def = new CraftDefinitionFuel(
+ recipe, burntime, replacements);
+ craftdef->registerCraft(def);
+ }
+ else
+ {
+ throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
+ }
+
+ lua_pop(L, 1);
+ return 0; /* number of results */
+}
+
+// setting_set(name, value)
+static int l_setting_set(lua_State *L)
+{
+ const char *name = luaL_checkstring(L, 1);
+ const char *value = luaL_checkstring(L, 2);
+ g_settings->set(name, value);
+ return 0;
+}
+
+// setting_get(name)
+static int l_setting_get(lua_State *L)
+{
+ const char *name = luaL_checkstring(L, 1);
+ try{
+ std::string value = g_settings->get(name);
+ lua_pushstring(L, value.c_str());
+ } catch(SettingNotFoundException &e){
+ lua_pushnil(L);
+ }
+ return 1;
+}
+
+// setting_getbool(name)
+static int l_setting_getbool(lua_State *L)
+{
+ const char *name = luaL_checkstring(L, 1);
+ try{
+ bool value = g_settings->getBool(name);
+ lua_pushboolean(L, value);
+ } catch(SettingNotFoundException &e){
+ lua_pushnil(L);
+ }
+ return 1;
+}
+
+// chat_send_all(text)
+static int l_chat_send_all(lua_State *L)
+{
+ const char *text = luaL_checkstring(L, 1);
+ // Get server from registry
+ Server *server = get_server(L);
+ // Send
+ server->notifyPlayers(narrow_to_wide(text));
+ return 0;
+}
+
+// chat_send_player(name, text)
+static int l_chat_send_player(lua_State *L)
+{
+ const char *name = luaL_checkstring(L, 1);
+ const char *text = luaL_checkstring(L, 2);
+ // Get server from registry
+ Server *server = get_server(L);
+ // Send
+ server->notifyPlayer(name, narrow_to_wide(text));
+ return 0;
+}
+
+// get_player_privs(name, text)
+static int l_get_player_privs(lua_State *L)
+{
+ const char *name = luaL_checkstring(L, 1);
+ // Get server from registry
+ Server *server = get_server(L);
+ // Do it
+ lua_newtable(L);
+ int table = lua_gettop(L);
+ std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
+ for(std::set<std::string>::const_iterator
+ i = privs_s.begin(); i != privs_s.end(); i++){
+ lua_pushboolean(L, true);
+ lua_setfield(L, table, i->c_str());
+ }
+ lua_pushvalue(L, table);
+ return 1;
+}
+
+// get_ban_list()
+static int l_get_ban_list(lua_State *L)
+{
+ lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
+ return 1;
+}
+
+// get_ban_description()
+static int l_get_ban_description(lua_State *L)
+{
+ const char * ip_or_name = luaL_checkstring(L, 1);
+ lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
+ return 1;
+}
+
+// ban_player()
+static int l_ban_player(lua_State *L)
+{
+ const char * name = luaL_checkstring(L, 1);
+ Player *player = get_env(L)->getPlayer(name);
+ if(player == NULL)
+ {
+ lua_pushboolean(L, false); // no such player
+ return 1;
+ }
+ try
+ {
+ Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
+ std::string ip_str = addr.serializeString();
+ get_server(L)->setIpBanned(ip_str, name);
+ }
+ catch(con::PeerNotFoundException) // unlikely
+ {
+ dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
+ lua_pushboolean(L, false); // error
+ return 1;
+ }
+ lua_pushboolean(L, true);
+ return 1;
+}
+
+// unban_player_or_ip()
+static int l_unban_player_of_ip(lua_State *L)
+{
+ const char * ip_or_name = luaL_checkstring(L, 1);
+ get_server(L)->unsetIpBanned(ip_or_name);
+ lua_pushboolean(L, true);
+ return 1;
+}
+
+// get_inventory(location)
+static int l_get_inventory(lua_State *L)
+{
+ InventoryLocation loc;
+
+ std::string type = checkstringfield(L, 1, "type");
+ if(type == "player"){
+ std::string name = checkstringfield(L, 1, "name");
+ loc.setPlayer(name);
+ } else if(type == "node"){
+ lua_getfield(L, 1, "pos");
+ v3s16 pos = check_v3s16(L, -1);
+ loc.setNodeMeta(pos);
+ } else if(type == "detached"){
+ std::string name = checkstringfield(L, 1, "name");
+ loc.setDetached(name);
+ }
+
+ if(get_server(L)->getInventory(loc) != NULL)
+ InvRef::create(L, loc);
+ else
+ lua_pushnil(L);
+ return 1;
+}
+
+// create_detached_inventory_raw(name)
+static int l_create_detached_inventory_raw(lua_State *L)
+{
+ const char *name = luaL_checkstring(L, 1);
+ if(get_server(L)->createDetachedInventory(name) != NULL){
+ InventoryLocation loc;
+ loc.setDetached(name);
+ InvRef::create(L, loc);
+ }else{
+ lua_pushnil(L);
+ }
+ return 1;
+}
+
+// show_formspec(playername,formname,formspec)
+static int l_show_formspec(lua_State *L)
+{
+ const char *playername = luaL_checkstring(L, 1);
+ const char *formname = luaL_checkstring(L, 2);
+ const char *formspec = luaL_checkstring(L, 3);
+
+ if(get_server(L)->showFormspec(playername,formspec,formname))
+ {
+ lua_pushboolean(L, true);
+ }else{
+ lua_pushboolean(L, false);
+ }
+ return 1;
+}
+
+// get_dig_params(groups, tool_capabilities[, time_from_last_punch])
+static int l_get_dig_params(lua_State *L)
+{
+ std::map<std::string, int> groups;
+ read_groups(L, 1, groups);
+ ToolCapabilities tp = read_tool_capabilities(L, 2);
+ if(lua_isnoneornil(L, 3))
+ push_dig_params(L, getDigParams(groups, &tp));
+ else
+ push_dig_params(L, getDigParams(groups, &tp,
+ luaL_checknumber(L, 3)));
+ return 1;
+}
+
+// get_hit_params(groups, tool_capabilities[, time_from_last_punch])
+static int l_get_hit_params(lua_State *L)
+{
+ std::map<std::string, int> groups;
+ read_groups(L, 1, groups);
+ ToolCapabilities tp = read_tool_capabilities(L, 2);
+ if(lua_isnoneornil(L, 3))
+ push_hit_params(L, getHitParams(groups, &tp));
+ else
+ push_hit_params(L, getHitParams(groups, &tp,
+ luaL_checknumber(L, 3)));
+ return 1;
+}
+
+// get_current_modname()
+static int l_get_current_modname(lua_State *L)
+{
+ lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
+ return 1;
+}
+
+// get_modpath(modname)
+static int l_get_modpath(lua_State *L)
+{
+ std::string modname = luaL_checkstring(L, 1);
+ // Do it
+ if(modname == "__builtin"){
+ std::string path = get_server(L)->getBuiltinLuaPath();
+ lua_pushstring(L, path.c_str());
+ return 1;
+ }
+ const ModSpec *mod = get_server(L)->getModSpec(modname);
+ if(!mod){
+ lua_pushnil(L);
+ return 1;
+ }
+ lua_pushstring(L, mod->path.c_str());
+ return 1;
+}
+
+// get_modnames()
+// the returned list is sorted alphabetically for you
+static int l_get_modnames(lua_State *L)
+{
+ // Get a list of mods
+ core::list<std::string> mods_unsorted, mods_sorted;
+ get_server(L)->getModNames(mods_unsorted);
+
+ // Take unsorted items from mods_unsorted and sort them into
+ // mods_sorted; not great performance but the number of mods on a
+ // server will likely be small.
+ for(core::list<std::string>::Iterator i = mods_unsorted.begin();
+ i != mods_unsorted.end(); i++)
+ {
+ bool added = false;
+ for(core::list<std::string>::Iterator x = mods_sorted.begin();
+ x != mods_unsorted.end(); x++)
+ {
+ // I doubt anybody using Minetest will be using
+ // anything not ASCII based :)
+ if((*i).compare(*x) <= 0)
+ {
+ mods_sorted.insert_before(x, *i);
+ added = true;
+ break;
+ }
+ }
+ if(!added)
+ mods_sorted.push_back(*i);
+ }
+
+ // Get the table insertion function from Lua.
+ lua_getglobal(L, "table");
+ lua_getfield(L, -1, "insert");
+ int insertion_func = lua_gettop(L);
+
+ // Package them up for Lua
+ lua_newtable(L);
+ int new_table = lua_gettop(L);
+ core::list<std::string>::Iterator i = mods_sorted.begin();
+ while(i != mods_sorted.end())
+ {
+ lua_pushvalue(L, insertion_func);
+ lua_pushvalue(L, new_table);
+ lua_pushstring(L, (*i).c_str());
+ if(lua_pcall(L, 2, 0, 0) != 0)
+ {
+ script_error(L, "error: %s", lua_tostring(L, -1));
+ }
+ i++;
+ }
+ return 1;
+}
+
+// get_worldpath()
+static int l_get_worldpath(lua_State *L)
+{
+ std::string worldpath = get_server(L)->getWorldPath();
+ lua_pushstring(L, worldpath.c_str());
+ return 1;
+}
+
+// sound_play(spec, parameters)
+static int l_sound_play(lua_State *L)
+{
+ SimpleSoundSpec spec;
+ read_soundspec(L, 1, spec);
+ ServerSoundParams params;
+ read_server_sound_params(L, 2, params);
+ s32 handle = get_server(L)->playSound(spec, params);
+ lua_pushinteger(L, handle);
+ return 1;
+}
+
+// sound_stop(handle)
+static int l_sound_stop(lua_State *L)
+{
+ int handle = luaL_checkinteger(L, 1);
+ get_server(L)->stopSound(handle);
+ return 0;
+}
+
+// is_singleplayer()
+static int l_is_singleplayer(lua_State *L)
+{
+ lua_pushboolean(L, get_server(L)->isSingleplayer());
+ return 1;
+}
+
+// get_password_hash(name, raw_password)
+static int l_get_password_hash(lua_State *L)
+{
+ std::string name = luaL_checkstring(L, 1);
+ std::string raw_password = luaL_checkstring(L, 2);
+ std::string hash = translatePassword(name,
+ narrow_to_wide(raw_password));
+ lua_pushstring(L, hash.c_str());
+ return 1;
+}
+
+// notify_authentication_modified(name)
+static int l_notify_authentication_modified(lua_State *L)
+{
+ std::string name = "";
+ if(lua_isstring(L, 1))
+ name = lua_tostring(L, 1);
+ get_server(L)->reportPrivsModified(name);
+ return 0;
+}
+
+// get_craft_result(input)
+static int l_get_craft_result(lua_State *L)
+{
+ int input_i = 1;
+ std::string method_s = getstringfield_default(L, input_i, "method", "normal");
+ enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
+ es_CraftMethod, CRAFT_METHOD_NORMAL);
+ int width = 1;
+ lua_getfield(L, input_i, "width");
+ if(lua_isnumber(L, -1))
+ width = luaL_checkinteger(L, -1);
+ lua_pop(L, 1);
+ lua_getfield(L, input_i, "items");
+ std::vector<ItemStack> items = read_items(L, -1);
+ lua_pop(L, 1); // items
+
+ IGameDef *gdef = get_server(L);
+ ICraftDefManager *cdef = gdef->cdef();
+ CraftInput input(method, width, items);
+ CraftOutput output;
+ bool got = cdef->getCraftResult(input, output, true, gdef);
+ lua_newtable(L); // output table
+ if(got){
+ ItemStack item;
+ item.deSerialize(output.item, gdef->idef());
+ LuaItemStack::create(L, item);
+ lua_setfield(L, -2, "item");
+ setintfield(L, -1, "time", output.time);
+ } else {
+ LuaItemStack::create(L, ItemStack());
+ lua_setfield(L, -2, "item");
+ setintfield(L, -1, "time", 0);
+ }
+ lua_newtable(L); // decremented input table
+ lua_pushstring(L, method_s.c_str());
+ lua_setfield(L, -2, "method");
+ lua_pushinteger(L, width);
+ lua_setfield(L, -2, "width");
+ push_items(L, input.items);
+ lua_setfield(L, -2, "items");
+ return 2;
+}
+
+// get_craft_recipe(result item)
+static int l_get_craft_recipe(lua_State *L)
+{
+ int k = 0;
+ char tmp[20];
+ int input_i = 1;
+ std::string o_item = luaL_checkstring(L,input_i);
+
+ IGameDef *gdef = get_server(L);
+ ICraftDefManager *cdef = gdef->cdef();
+ CraftInput input;
+ CraftOutput output(o_item,0);
+ bool got = cdef->getCraftRecipe(input, output, gdef);
+ lua_newtable(L); // output table
+ if(got){
+ lua_newtable(L);
+ for(std::vector<ItemStack>::const_iterator
+ i = input.items.begin();
+ i != input.items.end(); i++, k++)
+ {
+ if (i->empty())
+ {
+ continue;
+ }
+ sprintf(tmp,"%d",k);
+ lua_pushstring(L,tmp);
+ lua_pushstring(L,i->name.c_str());
+ lua_settable(L, -3);
+ }
+ lua_setfield(L, -2, "items");
+ setintfield(L, -1, "width", input.width);
+ switch (input.method) {
+ case CRAFT_METHOD_NORMAL:
+ lua_pushstring(L,"normal");
+ break;
+ case CRAFT_METHOD_COOKING:
+ lua_pushstring(L,"cooking");
+ break;
+ case CRAFT_METHOD_FUEL:
+ lua_pushstring(L,"fuel");
+ break;
+ default:
+ lua_pushstring(L,"unknown");
+ }
+ lua_setfield(L, -2, "type");
+ } else {
+ lua_pushnil(L);
+ lua_setfield(L, -2, "items");
+ setintfield(L, -1, "width", 0);
+ }
+ return 1;
+}
+
+// rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
+static int l_rollback_get_last_node_actor(lua_State *L)
+{
+ v3s16 p = read_v3s16(L, 1);
+ int range = luaL_checknumber(L, 2);
+ int seconds = luaL_checknumber(L, 3);
+ Server *server = get_server(L);
+ IRollbackManager *rollback = server->getRollbackManager();
+ v3s16 act_p;
+ int act_seconds = 0;
+ std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
+ lua_pushstring(L, actor.c_str());
+ push_v3s16(L, act_p);
+ lua_pushnumber(L, act_seconds);
+ return 3;
+}
+
+// rollback_revert_actions_by(actor, seconds) -> bool, log messages
+static int l_rollback_revert_actions_by(lua_State *L)
+{
+ std::string actor = luaL_checkstring(L, 1);
+ int seconds = luaL_checknumber(L, 2);
+ Server *server = get_server(L);
+ IRollbackManager *rollback = server->getRollbackManager();
+ std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
+ std::list<std::string> log;
+ bool success = server->rollbackRevertActions(actions, &log);
+ // Push boolean result
+ lua_pushboolean(L, success);
+ // Get the table insert function and push the log table
+ lua_getglobal(L, "table");
+ lua_getfield(L, -1, "insert");
+ int table_insert = lua_gettop(L);
+ lua_newtable(L);
+ int table = lua_gettop(L);
+ for(std::list<std::string>::const_iterator i = log.begin();
+ i != log.end(); i++)
+ {
+ lua_pushvalue(L, table_insert);
+ lua_pushvalue(L, table);
+ lua_pushstring(L, i->c_str());
+ if(lua_pcall(L, 2, 0, 0))
+ script_error(L, "error: %s", lua_tostring(L, -1));
+ }
+ lua_remove(L, -2); // Remove table
+ lua_remove(L, -2); // Remove insert
+ return 2;
+}
+
+static const struct luaL_Reg minetest_f [] = {
+ {"debug", l_debug},
+ {"log", l_log},
+ {"request_shutdown", l_request_shutdown},
+ {"get_server_status", l_get_server_status},
+ {"register_item_raw", l_register_item_raw},
+ {"register_alias_raw", l_register_alias_raw},
+ {"register_craft", l_register_craft},
+ {"register_biome", l_register_biome},
+ {"register_biome_groups", l_register_biome_groups},
+ {"setting_set", l_setting_set},
+ {"setting_get", l_setting_get},
+ {"setting_getbool", l_setting_getbool},
+ {"chat_send_all", l_chat_send_all},
+ {"chat_send_player", l_chat_send_player},
+ {"get_player_privs", l_get_player_privs},
+ {"get_ban_list", l_get_ban_list},
+ {"get_ban_description", l_get_ban_description},
+ {"ban_player", l_ban_player},
+ {"unban_player_or_ip", l_unban_player_of_ip},
+ {"get_inventory", l_get_inventory},
+ {"create_detached_inventory_raw", l_create_detached_inventory_raw},
+ {"show_formspec", l_show_formspec},
+ {"get_dig_params", l_get_dig_params},
+ {"get_hit_params", l_get_hit_params},
+ {"get_current_modname", l_get_current_modname},
+ {"get_modpath", l_get_modpath},
+ {"get_modnames", l_get_modnames},
+ {"get_worldpath", l_get_worldpath},
+ {"sound_play", l_sound_play},
+ {"sound_stop", l_sound_stop},
+ {"is_singleplayer", l_is_singleplayer},
+ {"get_password_hash", l_get_password_hash},
+ {"notify_authentication_modified", l_notify_authentication_modified},
+ {"get_craft_result", l_get_craft_result},
+ {"get_craft_recipe", l_get_craft_recipe},
+ {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
+ {"rollback_revert_actions_by", l_rollback_revert_actions_by},
+ {NULL, NULL}
+};
+
+/*
+ Main export function
+*/
+
+void scriptapi_export(lua_State *L, Server *server)
+{
+ realitycheck(L);
+ assert(lua_checkstack(L, 20));
+ verbosestream<<"scriptapi_export()"<<std::endl;
+ StackUnroller stack_unroller(L);
+
+ // Store server as light userdata in registry
+ lua_pushlightuserdata(L, server);
+ lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
+
+ // Register global functions in table minetest
+ lua_newtable(L);
+ luaL_register(L, NULL, minetest_f);
+ lua_setglobal(L, "minetest");
+
+ // Get the main minetest table
+ lua_getglobal(L, "minetest");
+
+ // Add tables to minetest
+ lua_newtable(L);
+ lua_setfield(L, -2, "object_refs");
+ lua_newtable(L);
+ lua_setfield(L, -2, "luaentities");
+
+ // Register wrappers
+ LuaItemStack::Register(L);
+ InvRef::Register(L);
+ NodeMetaRef::Register(L);
+ NodeTimerRef::Register(L);
+ ObjectRef::Register(L);
+ EnvRef::Register(L);
+ LuaPseudoRandom::Register(L);
+ LuaPerlinNoise::Register(L);
+}
+
+bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
+ const std::string &modname)
+{
+ ModNameStorer modnamestorer(L, modname);
+
+ if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
+ "0123456789_")){
+ errorstream<<"Error loading mod \""<<modname
+ <<"\": modname does not follow naming conventions: "
+ <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
+ return false;
+ }
+
+ bool success = false;
+
+ try{
+ success = script_load(L, scriptpath.c_str());
+ }
+ catch(LuaError &e){
+ errorstream<<"Error loading mod \""<<modname
+ <<"\": "<<e.what()<<std::endl;
+ }
+
+ return success;
+}
+
+void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
+{
+ realitycheck(L);
+ assert(lua_checkstack(L, 20));
+ verbosestream<<"scriptapi_add_environment"<<std::endl;
+ StackUnroller stack_unroller(L);
+
+ // Create EnvRef on stack
+ EnvRef::create(L, env);
+ int envref = lua_gettop(L);
+
+ // minetest.env = envref
+ lua_getglobal(L, "minetest");
+ luaL_checktype(L, -1, LUA_TTABLE);
+ lua_pushvalue(L, envref);
+ lua_setfield(L, -2, "env");
+
+ // Store environment as light userdata in registry
+ lua_pushlightuserdata(L, env);
+ lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
+
+ /*
+ Add ActiveBlockModifiers to environment
+ */
+
+ // Get minetest.registered_abms
+ lua_getglobal(L, "minetest");
+ lua_getfield(L, -1, "registered_abms");
+ luaL_checktype(L, -1, LUA_TTABLE);
+ int registered_abms = lua_gettop(L);
+
+ if(lua_istable(L, registered_abms)){
+ int table = lua_gettop(L);
+ lua_pushnil(L);
+ while(lua_next(L, table) != 0){
+ // key at index -2 and value at index -1
+ int id = lua_tonumber(L, -2);
+ int current_abm = lua_gettop(L);
+
+ std::set<std::string> trigger_contents;
+ lua_getfield(L, current_abm, "nodenames");
+ if(lua_istable(L, -1)){
+ int table = lua_gettop(L);
+ lua_pushnil(L);
+ while(lua_next(L, table) != 0){
+ // key at index -2 and value at index -1
+ luaL_checktype(L, -1, LUA_TSTRING);
+ trigger_contents.insert(lua_tostring(L, -1));
+ // removes value, keeps key for next iteration
+ lua_pop(L, 1);
+ }
+ } else if(lua_isstring(L, -1)){
+ trigger_contents.insert(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
+
+ std::set<std::string> required_neighbors;
+ lua_getfield(L, current_abm, "neighbors");
+ if(lua_istable(L, -1)){
+ int table = lua_gettop(L);
+ lua_pushnil(L);
+ while(lua_next(L, table) != 0){
+ // key at index -2 and value at index -1
+ luaL_checktype(L, -1, LUA_TSTRING);
+ required_neighbors.insert(lua_tostring(L, -1));
+ // removes value, keeps key for next iteration
+ lua_pop(L, 1);
+ }
+ } else if(lua_isstring(L, -1)){
+ required_neighbors.insert(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
+
+ float trigger_interval = 10.0;
+ getfloatfield(L, current_abm, "interval", trigger_interval);
+
+ int trigger_chance = 50;
+ getintfield(L, current_abm, "chance", trigger_chance);
+
+ LuaABM *abm = new LuaABM(L, id, trigger_contents,
+ required_neighbors, trigger_interval, trigger_chance);
+
+ env->addActiveBlockModifier(abm);
+
+ // removes value, keeps key for next iteration
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+}
+
+#if 0
+// Dump stack top with the dump2 function
+static void dump2(lua_State *L, const char *name)
+{
+ // Dump object (debug)
+ lua_getglobal(L, "dump2");
+ luaL_checktype(L, -1, LUA_TFUNCTION);
+ lua_pushvalue(L, -2); // Get previous stack top as first parameter
+ lua_pushstring(L, name);
+ if(lua_pcall(L, 2, 0, 0))
+ script_error(L, "error: %s", lua_tostring(L, -1));
+}
+#endif
+
+/*
+ object_reference
+*/
+
+void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
+{
+ realitycheck(L);
+ assert(lua_checkstack(L, 20));
+ //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
+ StackUnroller stack_unroller(L);
+
+ // Create object on stack
+ ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
+ int object = lua_gettop(L);
+
+ // Get minetest.object_refs table
+ lua_getglobal(L, "minetest");
+ lua_getfield(L, -1, "object_refs");
+ luaL_checktype(L, -1, LUA_TTABLE);
+ int objectstable = lua_gettop(L);
+
+ // object_refs[id] = object
+ lua_pushnumber(L, cobj->getId()); // Push id
+ lua_pushvalue(L, object); // Copy object to top of stack
+ lua_settable(L, objectstable);
+}
+
+void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
+{
+ realitycheck(L);
+ assert(lua_checkstack(L, 20));
+ //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
+ StackUnroller stack_unroller(L);
+
+ // Get minetest.object_refs table
+ lua_getglobal(L, "minetest");
+ lua_getfield(L, -1, "object_refs");
+ luaL_checktype(L, -1, LUA_TTABLE);
+ int objectstable = lua_gettop(L);
+
+ // Get object_refs[id]
+ lua_pushnumber(L, cobj->getId()); // Push id
+ lua_gettable(L, objectstable);
+ // Set object reference to NULL
+ ObjectRef::set_null(L);
+ lua_pop(L, 1); // pop object
+
+ // Set object_refs[id] = nil
+ lua_pushnumber(L, cobj->getId()); // Push id
+ lua_pushnil(L);
+ lua_settable(L, objectstable);
+}
+
+/*
+ misc
+*/
+
+// What scriptapi_run_callbacks does with the return values of callbacks.
+// Regardless of the mode, if only one callback is defined,
+// its return value is the total return value.
+// Modes only affect the case where 0 or >= 2 callbacks are defined.
+enum RunCallbacksMode
+{
+ // Returns the return value of the first callback
+ // Returns nil if list of callbacks is empty
+ RUN_CALLBACKS_MODE_FIRST,
+ // Returns the return value of the last callback
+ // Returns nil if list of callbacks is empty
+ RUN_CALLBACKS_MODE_LAST,
+ // If any callback returns a false value, the first such is returned
+ // Otherwise, the first callback's return value (trueish) is returned
+ // Returns true if list of callbacks is empty
+ RUN_CALLBACKS_MODE_AND,
+ // Like above, but stops calling callbacks (short circuit)
+ // after seeing the first false value
+ RUN_CALLBACKS_MODE_AND_SC,
+ // If any callback returns a true value, the first such is returned
+ // Otherwise, the first callback's return value (falseish) is returned
+ // Returns false if list of callbacks is empty
+ RUN_CALLBACKS_MODE_OR,
+ // Like above, but stops calling callbacks (short circuit)
+ // after seeing the first true value
+ RUN_CALLBACKS_MODE_OR_SC,
+ // Note: "a true value" and "a false value" refer to values that
+ // are converted by lua_toboolean to true or false, respectively.
+};
+
+// Push the list of callbacks (a lua table).
+// Then push nargs arguments.
+// Then call this function, which
+// - runs the callbacks
+// - removes the table and arguments from the lua stack
+// - pushes the return value, computed depending on mode
+static void scriptapi_run_callbacks(lua_State *L, int nargs,
+ RunCallbacksMode mode)
+{
+ // Insert the return value into the lua stack, below the table
+ assert(lua_gettop(L) >= nargs + 1);
+ lua_pushnil(L);
+ lua_insert(L, -(nargs + 1) - 1);
+ // Stack now looks like this:
+ // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
+
+ int rv = lua_gettop(L) - nargs - 1;
+ int table = rv + 1;
+ int arg = table + 1;
+
+ luaL_checktype(L, table, LUA_TTABLE);
+
+ // Foreach
+ lua_pushnil(L);
+ bool first_loop = true;
+ while(lua_next(L, table) != 0){
+ // key at index -2 and value at index -1
+ luaL_checktype(L, -1, LUA_TFUNCTION);
+ // Call function
+ for(int i = 0; i < nargs; i++)
+ lua_pushvalue(L, arg+i);
+ if(lua_pcall(L, nargs, 1, 0))
+ script_error(L, "error: %s", lua_tostring(L, -1));
+
+ // Move return value to designated space in stack
+ // Or pop it
+ if(first_loop){
+ // Result of first callback is always moved
+ lua_replace(L, rv);
+ first_loop = false;
+ } else {
+ // Otherwise, what happens depends on the mode
+ if(mode == RUN_CALLBACKS_MODE_FIRST)
+ lua_pop(L, 1);
+ else if(mode == RUN_CALLBACKS_MODE_LAST)
+ lua_replace(L, rv);
+ else if(mode == RUN_CALLBACKS_MODE_AND ||
+ mode == RUN_CALLBACKS_MODE_AND_SC){
+ if((bool)lua_toboolean(L, rv) == true &&
+ (bool)lua_toboolean(L, -1) == false)
+ lua_replace(L, rv);
+ else
+ lua_pop(L, 1);
+ }
+ else if(mode == RUN_CALLBACKS_MODE_OR ||
+ mode == RUN_CALLBACKS_MODE_OR_SC){
+ if((bool)lua_toboolean(L, rv) == false &&
+ (bool)lua_toboolean(L, -1) == true)
+ lua_replace(L, rv);
+ else
+ lua_pop(L, 1);
+ }
+ else
+ assert(0);
+ }
+
+ // Handle short circuit modes
+ if(mode == RUN_CALLBACKS_MODE_AND_SC &&
+ (bool)lua_toboolean(L, rv) == false)
+ break;
+ else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
+ (bool)lua_toboolean(L, rv) == true)
+ break;
+
+ // value removed, keep key for next iteration
+ }
+
+ // Remove stuff from stack, leaving only the return value
+ lua_settop(L, rv);