3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "scriptapi.h"
30 #include "settings.h" // For accessing g_settings
31 #include "main.h" // For g_settings
37 #include "scriptapi_types.h"
38 #include "scriptapi_env.h"
39 #include "scriptapi_nodetimer.h"
40 #include "scriptapi_inventory.h"
41 #include "scriptapi_nodemeta.h"
42 #include "scriptapi_object.h"
43 #include "scriptapi_noise.h"
44 #include "scriptapi_common.h"
45 #include "scriptapi_item.h"
46 #include "scriptapi_content.h"
47 #include "scriptapi_craft.h"
48 #include "scriptapi_particles.h"
50 /*****************************************************************************/
52 /*****************************************************************************/
59 ModNameStorer(lua_State *L_, const std::string modname):
62 // Store current modname in registry
63 lua_pushstring(L, modname.c_str());
64 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
68 // Clear current modname in registry
70 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
74 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
75 const std::string &modname)
77 ModNameStorer modnamestorer(L, modname);
79 if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
81 errorstream<<"Error loading mod \""<<modname
82 <<"\": modname does not follow naming conventions: "
83 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
90 success = script_load(L, scriptpath.c_str());
93 errorstream<<"Error loading mod \""<<modname
94 <<"\": "<<e.what()<<std::endl;
101 /*****************************************************************************/
103 /*****************************************************************************/
108 static void read_privileges(lua_State *L, int index,
109 std::set<std::string> &result)
115 while(lua_next(L, index) != 0){
116 // key at index -2 and value at index -1
117 std::string key = luaL_checkstring(L, -2);
118 bool value = lua_toboolean(L, -1);
121 // removes value, keeps key for next iteration
126 static void get_auth_handler(lua_State *L)
128 lua_getglobal(L, "minetest");
129 lua_getfield(L, -1, "registered_auth_handler");
130 if(lua_isnil(L, -1)){
132 lua_getfield(L, -1, "builtin_auth_handler");
134 if(lua_type(L, -1) != LUA_TTABLE)
135 throw LuaError(L, "Authentication handler table not valid");
138 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
139 std::string *dst_password, std::set<std::string> *dst_privs)
142 assert(lua_checkstack(L, 20));
143 StackUnroller stack_unroller(L);
146 lua_getfield(L, -1, "get_auth");
147 if(lua_type(L, -1) != LUA_TFUNCTION)
148 throw LuaError(L, "Authentication handler missing get_auth");
149 lua_pushstring(L, playername.c_str());
150 if(lua_pcall(L, 1, 1, 0))
151 script_error(L, "error: %s", lua_tostring(L, -1));
153 // nil = login not allowed
156 luaL_checktype(L, -1, LUA_TTABLE);
158 std::string password;
159 bool found = getstringfield(L, -1, "password", password);
161 throw LuaError(L, "Authentication handler didn't return password");
163 *dst_password = password;
165 lua_getfield(L, -1, "privileges");
166 if(!lua_istable(L, -1))
168 "Authentication handler didn't return privilege table");
170 read_privileges(L, -1, *dst_privs);
176 void scriptapi_create_auth(lua_State *L, const std::string &playername,
177 const std::string &password)
180 assert(lua_checkstack(L, 20));
181 StackUnroller stack_unroller(L);
184 lua_getfield(L, -1, "create_auth");
185 if(lua_type(L, -1) != LUA_TFUNCTION)
186 throw LuaError(L, "Authentication handler missing create_auth");
187 lua_pushstring(L, playername.c_str());
188 lua_pushstring(L, password.c_str());
189 if(lua_pcall(L, 2, 0, 0))
190 script_error(L, "error: %s", lua_tostring(L, -1));
193 bool scriptapi_set_password(lua_State *L, const std::string &playername,
194 const std::string &password)
197 assert(lua_checkstack(L, 20));
198 StackUnroller stack_unroller(L);
201 lua_getfield(L, -1, "set_password");
202 if(lua_type(L, -1) != LUA_TFUNCTION)
203 throw LuaError(L, "Authentication handler missing set_password");
204 lua_pushstring(L, playername.c_str());
205 lua_pushstring(L, password.c_str());
206 if(lua_pcall(L, 2, 1, 0))
207 script_error(L, "error: %s", lua_tostring(L, -1));
208 return lua_toboolean(L, -1);
211 /*****************************************************************************/
213 /*****************************************************************************/
217 void read_groups(lua_State *L, int index,
218 std::map<std::string, int> &result)
220 if (!lua_istable(L,index))
226 while(lua_next(L, index) != 0){
227 // key at index -2 and value at index -1
228 std::string name = luaL_checkstring(L, -2);
229 int rating = luaL_checkinteger(L, -1);
230 result[name] = rating;
231 // removes value, keeps key for next iteration
236 struct EnumString es_BiomeTerrainType[] =
238 {BIOME_TERRAIN_NORMAL, "normal"},
239 {BIOME_TERRAIN_LIQUID, "liquid"},
240 {BIOME_TERRAIN_NETHER, "nether"},
241 {BIOME_TERRAIN_AETHER, "aether"},
242 {BIOME_TERRAIN_FLAT, "flat"},
246 struct EnumString es_OreType[] =
248 {ORE_SCATTER, "scatter"},
249 {ORE_SHEET, "sheet"},
250 {ORE_CLAYLIKE, "claylike"},
254 /*****************************************************************************/
256 /*****************************************************************************/
261 static void set_dig_params(lua_State *L, int table,
262 const DigParams ¶ms)
264 setboolfield(L, table, "diggable", params.diggable);
265 setfloatfield(L, table, "time", params.time);
266 setintfield(L, table, "wear", params.wear);
269 static void push_dig_params(lua_State *L,
270 const DigParams ¶ms)
273 set_dig_params(L, -1, params);
280 static void set_hit_params(lua_State *L, int table,
281 const HitParams ¶ms)
283 setintfield(L, table, "hp", params.hp);
284 setintfield(L, table, "wear", params.wear);
287 static void push_hit_params(lua_State *L,
288 const HitParams ¶ms)
291 set_hit_params(L, -1, params);
298 static void read_server_sound_params(lua_State *L, int index,
299 ServerSoundParams ¶ms)
302 index = lua_gettop(L) + 1 + index;
304 params = ServerSoundParams();
305 if(lua_istable(L, index)){
306 getfloatfield(L, index, "gain", params.gain);
307 getstringfield(L, index, "to_player", params.to_player);
308 lua_getfield(L, index, "pos");
309 if(!lua_isnil(L, -1)){
310 v3f p = read_v3f(L, -1)*BS;
312 params.type = ServerSoundParams::SSP_POSITIONAL;
315 lua_getfield(L, index, "object");
316 if(!lua_isnil(L, -1)){
317 ObjectRef *ref = ObjectRef::checkobject(L, -1);
318 ServerActiveObject *sao = ObjectRef::getobject(ref);
320 params.object = sao->getId();
321 params.type = ServerSoundParams::SSP_OBJECT;
325 params.max_hear_distance = BS*getfloatfield_default(L, index,
326 "max_hear_distance", params.max_hear_distance/BS);
327 getboolfield(L, index, "loop", params.loop);
331 /*****************************************************************************/
333 /*****************************************************************************/
335 // Push the list of callbacks (a lua table).
336 // Then push nargs arguments.
337 // Then call this function, which
338 // - runs the callbacks
339 // - removes the table and arguments from the lua stack
340 // - pushes the return value, computed depending on mode
341 void scriptapi_run_callbacks(lua_State *L, int nargs,
342 RunCallbacksMode mode)
344 // Insert the return value into the lua stack, below the table
345 assert(lua_gettop(L) >= nargs + 1);
347 lua_insert(L, -(nargs + 1) - 1);
348 // Stack now looks like this:
349 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
351 int rv = lua_gettop(L) - nargs - 1;
355 luaL_checktype(L, table, LUA_TTABLE);
359 bool first_loop = true;
360 while(lua_next(L, table) != 0){
361 // key at index -2 and value at index -1
362 luaL_checktype(L, -1, LUA_TFUNCTION);
364 for(int i = 0; i < nargs; i++)
365 lua_pushvalue(L, arg+i);
366 if(lua_pcall(L, nargs, 1, 0))
367 script_error(L, "error: %s", lua_tostring(L, -1));
369 // Move return value to designated space in stack
372 // Result of first callback is always moved
376 // Otherwise, what happens depends on the mode
377 if(mode == RUN_CALLBACKS_MODE_FIRST)
379 else if(mode == RUN_CALLBACKS_MODE_LAST)
381 else if(mode == RUN_CALLBACKS_MODE_AND ||
382 mode == RUN_CALLBACKS_MODE_AND_SC){
383 if((bool)lua_toboolean(L, rv) == true &&
384 (bool)lua_toboolean(L, -1) == false)
389 else if(mode == RUN_CALLBACKS_MODE_OR ||
390 mode == RUN_CALLBACKS_MODE_OR_SC){
391 if((bool)lua_toboolean(L, rv) == false &&
392 (bool)lua_toboolean(L, -1) == true)
401 // Handle short circuit modes
402 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
403 (bool)lua_toboolean(L, rv) == false)
405 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
406 (bool)lua_toboolean(L, rv) == true)
409 // value removed, keep key for next iteration
412 // Remove stuff from stack, leaving only the return value
415 // Fix return value in case no callbacks were called
417 if(mode == RUN_CALLBACKS_MODE_AND ||
418 mode == RUN_CALLBACKS_MODE_AND_SC){
420 lua_pushboolean(L, true);
422 else if(mode == RUN_CALLBACKS_MODE_OR ||
423 mode == RUN_CALLBACKS_MODE_OR_SC){
425 lua_pushboolean(L, false);
430 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
431 const std::string &message)
434 assert(lua_checkstack(L, 20));
435 StackUnroller stack_unroller(L);
437 // Get minetest.registered_on_chat_messages
438 lua_getglobal(L, "minetest");
439 lua_getfield(L, -1, "registered_on_chat_messages");
441 lua_pushstring(L, name.c_str());
442 lua_pushstring(L, message.c_str());
443 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
444 bool ate = lua_toboolean(L, -1);
448 void scriptapi_on_shutdown(lua_State *L)
451 assert(lua_checkstack(L, 20));
452 StackUnroller stack_unroller(L);
454 // Get registered shutdown hooks
455 lua_getglobal(L, "minetest");
456 lua_getfield(L, -1, "registered_on_shutdown");
458 scriptapi_run_callbacks(L, 0, RUN_CALLBACKS_MODE_FIRST);
461 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
464 assert(lua_checkstack(L, 20));
465 StackUnroller stack_unroller(L);
467 // Get minetest.registered_on_newplayers
468 lua_getglobal(L, "minetest");
469 lua_getfield(L, -1, "registered_on_newplayers");
471 objectref_get_or_create(L, player);
472 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
475 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
478 assert(lua_checkstack(L, 20));
479 StackUnroller stack_unroller(L);
481 // Get minetest.registered_on_dieplayers
482 lua_getglobal(L, "minetest");
483 lua_getfield(L, -1, "registered_on_dieplayers");
485 objectref_get_or_create(L, player);
486 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
489 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
492 assert(lua_checkstack(L, 20));
493 StackUnroller stack_unroller(L);
495 // Get minetest.registered_on_respawnplayers
496 lua_getglobal(L, "minetest");
497 lua_getfield(L, -1, "registered_on_respawnplayers");
499 objectref_get_or_create(L, player);
500 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
501 bool positioning_handled_by_some = lua_toboolean(L, -1);
502 return positioning_handled_by_some;
505 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
508 assert(lua_checkstack(L, 20));
509 StackUnroller stack_unroller(L);
511 // Get minetest.registered_on_joinplayers
512 lua_getglobal(L, "minetest");
513 lua_getfield(L, -1, "registered_on_joinplayers");
515 objectref_get_or_create(L, player);
516 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
519 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
522 assert(lua_checkstack(L, 20));
523 StackUnroller stack_unroller(L);
525 // Get minetest.registered_on_leaveplayers
526 lua_getglobal(L, "minetest");
527 lua_getfield(L, -1, "registered_on_leaveplayers");
529 objectref_get_or_create(L, player);
530 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
536 void scriptapi_on_player_receive_fields(lua_State *L,
537 ServerActiveObject *player,
538 const std::string &formname,
539 const std::map<std::string, std::string> &fields)
542 assert(lua_checkstack(L, 20));
543 StackUnroller stack_unroller(L);
545 // Get minetest.registered_on_chat_messages
546 lua_getglobal(L, "minetest");
547 lua_getfield(L, -1, "registered_on_player_receive_fields");
550 objectref_get_or_create(L, player);
552 lua_pushstring(L, formname.c_str());
555 for(std::map<std::string, std::string>::const_iterator
556 i = fields.begin(); i != fields.end(); i++){
557 const std::string &name = i->first;
558 const std::string &value = i->second;
559 lua_pushstring(L, name.c_str());
560 lua_pushlstring(L, value.c_str(), value.size());
563 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
565 /*****************************************************************************/
567 /*****************************************************************************/
570 // Writes a line to dstream
571 static int l_debug(lua_State *L)
573 std::string text = lua_tostring(L, 1);
574 dstream << text << std::endl;
578 // log([level,] text)
579 // Writes a line to the logger.
580 // The one-argument version logs to infostream.
581 // The two-argument version accept a log level: error, action, info, or verbose.
582 static int l_log(lua_State *L)
585 LogMessageLevel level = LMT_INFO;
588 text = lua_tostring(L, 1);
592 std::string levelname = luaL_checkstring(L, 1);
593 text = luaL_checkstring(L, 2);
594 if(levelname == "error")
596 else if(levelname == "action")
598 else if(levelname == "verbose")
601 log_printline(level, text);
605 // request_shutdown()
606 static int l_request_shutdown(lua_State *L)
608 get_server(L)->requestShutdown();
612 // get_server_status()
613 static int l_get_server_status(lua_State *L)
615 lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
619 // register_biome_groups({frequencies})
620 static int l_register_biome_groups(lua_State *L)
622 luaL_checktype(L, 1, LUA_TTABLE);
625 BiomeDefManager *bmgr = get_server(L)->getBiomeDef();
627 verbosestream << "register_biome_groups: BiomeDefManager not active" << std::endl;
632 for (int i = 1; lua_next(L, index) != 0; i++) {
633 bmgr->addBiomeGroup(lua_tonumber(L, -1));
641 // register_biome({lots of stuff})
642 static int l_register_biome(lua_State *L)
644 luaL_checktype(L, 1, LUA_TTABLE);
645 int index = 1, groupid;
646 std::string nodename;
648 IWritableNodeDefManager *ndef = get_server(L)->getWritableNodeDefManager();
649 BiomeDefManager *bmgr = get_server(L)->getBiomeDef();
651 verbosestream << "register_biome: BiomeDefManager not active" << std::endl;
655 groupid = getintfield_default(L, index, "group_id", 0);
657 enum BiomeTerrainType terrain = (BiomeTerrainType)getenumfield(L, index,
658 "terrain_type", es_BiomeTerrainType, BIOME_TERRAIN_NORMAL);
659 Biome *b = bmgr->createBiome(terrain);
661 b->name = getstringfield_default(L, index, "name", "");
663 if (getstringfield(L, index, "node_top", nodename))
664 b->n_top = MapNode(ndef->getId(nodename));
666 b->n_top = MapNode(CONTENT_IGNORE);
668 if (getstringfield(L, index, "node_filler", nodename))
669 b->n_filler = MapNode(ndef->getId(nodename));
671 b->n_filler = b->n_top;
673 b->ntopnodes = getintfield_default(L, index, "num_top_nodes", 0);
675 b->height_min = getintfield_default(L, index, "height_min", 0);
676 b->height_max = getintfield_default(L, index, "height_max", 0);
677 b->heat_min = getfloatfield_default(L, index, "heat_min", 0.);
678 b->heat_max = getfloatfield_default(L, index, "heat_max", 0.);
679 b->humidity_min = getfloatfield_default(L, index, "humidity_min", 0.);
680 b->humidity_max = getfloatfield_default(L, index, "humidity_max", 0.);
682 b->np = new NoiseParams; // should read an entire NoiseParams later on...
683 getfloatfield(L, index, "scale", b->np->scale);
684 getfloatfield(L, index, "offset", b->np->offset);
686 b->groupid = (s8)groupid;
687 b->flags = 0; //reserved
691 verbosestream << "register_biome: " << b->name << std::endl;
696 static int l_register_ore(lua_State *L)
699 luaL_checktype(L, index, LUA_TTABLE);
701 IWritableNodeDefManager *ndef = get_server(L)->getWritableNodeDefManager();
702 EmergeManager *emerge = get_server(L)->getEmergeManager();
704 enum OreType oretype = (OreType)getenumfield(L, index,
705 "ore_type", es_OreType, ORE_SCATTER);
706 Ore *ore = createOre(oretype);
708 errorstream << "register_ore: ore_type "
709 << oretype << " not implemented";
713 ore->ore_name = getstringfield_default(L, index, "ore", "");
714 ore->wherein_name = getstringfield_default(L, index, "wherein", "");
715 ore->clust_scarcity = getintfield_default(L, index, "clust_scarcity", 1);
716 ore->clust_num_ores = getintfield_default(L, index, "clust_num_ores", 1);
717 ore->clust_size = getintfield_default(L, index, "clust_size", 0);
718 ore->height_min = getintfield_default(L, index, "height_min", 0);
719 ore->height_max = getintfield_default(L, index, "height_max", 0);
720 ore->flags = getflagsfield(L, index, "flags", flagdesc_ore);
721 ore->nthresh = getfloatfield_default(L, index, "noise_threshhold", 0.);
723 lua_getfield(L, index, "noise_params");
724 ore->np = read_noiseparams(L, -1);
729 if (ore->clust_scarcity <= 0 || ore->clust_num_ores <= 0) {
730 errorstream << "register_ore: clust_scarcity and clust_num_ores"
731 " must be greater than 0" << std::endl;
736 emerge->ores.push_back(ore);
738 verbosestream << "register_ore: ore '" << ore->ore_name
739 << "' registered" << std::endl;
744 // setting_set(name, value)
745 static int l_setting_set(lua_State *L)
747 const char *name = luaL_checkstring(L, 1);
748 const char *value = luaL_checkstring(L, 2);
749 g_settings->set(name, value);
754 static int l_setting_get(lua_State *L)
756 const char *name = luaL_checkstring(L, 1);
758 std::string value = g_settings->get(name);
759 lua_pushstring(L, value.c_str());
760 } catch(SettingNotFoundException &e){
766 // setting_getbool(name)
767 static int l_setting_getbool(lua_State *L)
769 const char *name = luaL_checkstring(L, 1);
771 bool value = g_settings->getBool(name);
772 lua_pushboolean(L, value);
773 } catch(SettingNotFoundException &e){
780 static int l_setting_save(lua_State *L)
782 get_server(L)->saveConfig();
786 // chat_send_all(text)
787 static int l_chat_send_all(lua_State *L)
789 const char *text = luaL_checkstring(L, 1);
790 // Get server from registry
791 Server *server = get_server(L);
793 server->notifyPlayers(narrow_to_wide(text));
797 // chat_send_player(name, text)
798 static int l_chat_send_player(lua_State *L)
800 const char *name = luaL_checkstring(L, 1);
801 const char *text = luaL_checkstring(L, 2);
802 // Get server from registry
803 Server *server = get_server(L);
805 server->notifyPlayer(name, narrow_to_wide(text));
809 // get_player_privs(name, text)
810 static int l_get_player_privs(lua_State *L)
812 const char *name = luaL_checkstring(L, 1);
813 // Get server from registry
814 Server *server = get_server(L);
817 int table = lua_gettop(L);
818 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
819 for(std::set<std::string>::const_iterator
820 i = privs_s.begin(); i != privs_s.end(); i++){
821 lua_pushboolean(L, true);
822 lua_setfield(L, table, i->c_str());
824 lua_pushvalue(L, table);
829 static int l_get_ban_list(lua_State *L)
831 lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
835 // get_ban_description()
836 static int l_get_ban_description(lua_State *L)
838 const char * ip_or_name = luaL_checkstring(L, 1);
839 lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
844 static int l_ban_player(lua_State *L)
846 const char * name = luaL_checkstring(L, 1);
847 Player *player = get_env(L)->getPlayer(name);
850 lua_pushboolean(L, false); // no such player
855 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
856 std::string ip_str = addr.serializeString();
857 get_server(L)->setIpBanned(ip_str, name);
859 catch(con::PeerNotFoundException) // unlikely
861 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
862 lua_pushboolean(L, false); // error
865 lua_pushboolean(L, true);
869 // unban_player_or_ip()
870 static int l_unban_player_of_ip(lua_State *L)
872 const char * ip_or_name = luaL_checkstring(L, 1);
873 get_server(L)->unsetIpBanned(ip_or_name);
874 lua_pushboolean(L, true);
878 // show_formspec(playername,formname,formspec)
879 static int l_show_formspec(lua_State *L)
881 const char *playername = luaL_checkstring(L, 1);
882 const char *formname = luaL_checkstring(L, 2);
883 const char *formspec = luaL_checkstring(L, 3);
885 if(get_server(L)->showFormspec(playername,formspec,formname))
887 lua_pushboolean(L, true);
889 lua_pushboolean(L, false);
894 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
895 static int l_get_dig_params(lua_State *L)
897 std::map<std::string, int> groups;
898 read_groups(L, 1, groups);
899 ToolCapabilities tp = read_tool_capabilities(L, 2);
900 if(lua_isnoneornil(L, 3))
901 push_dig_params(L, getDigParams(groups, &tp));
903 push_dig_params(L, getDigParams(groups, &tp,
904 luaL_checknumber(L, 3)));
908 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
909 static int l_get_hit_params(lua_State *L)
911 std::map<std::string, int> groups;
912 read_groups(L, 1, groups);
913 ToolCapabilities tp = read_tool_capabilities(L, 2);
914 if(lua_isnoneornil(L, 3))
915 push_hit_params(L, getHitParams(groups, &tp));
917 push_hit_params(L, getHitParams(groups, &tp,
918 luaL_checknumber(L, 3)));
922 // get_current_modname()
923 static int l_get_current_modname(lua_State *L)
925 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
929 // get_modpath(modname)
930 static int l_get_modpath(lua_State *L)
932 std::string modname = luaL_checkstring(L, 1);
934 if(modname == "__builtin"){
935 std::string path = get_server(L)->getBuiltinLuaPath();
936 lua_pushstring(L, path.c_str());
939 const ModSpec *mod = get_server(L)->getModSpec(modname);
944 lua_pushstring(L, mod->path.c_str());
949 // the returned list is sorted alphabetically for you
950 static int l_get_modnames(lua_State *L)
952 // Get a list of mods
953 std::list<std::string> mods_unsorted, mods_sorted;
954 get_server(L)->getModNames(mods_unsorted);
956 // Take unsorted items from mods_unsorted and sort them into
957 // mods_sorted; not great performance but the number of mods on a
958 // server will likely be small.
959 for(std::list<std::string>::iterator i = mods_unsorted.begin();
960 i != mods_unsorted.end(); ++i)
963 for(std::list<std::string>::iterator x = mods_sorted.begin();
964 x != mods_sorted.end(); ++x)
966 // I doubt anybody using Minetest will be using
967 // anything not ASCII based :)
968 if((*i).compare(*x) <= 0)
970 mods_sorted.insert(x, *i);
976 mods_sorted.push_back(*i);
979 // Get the table insertion function from Lua.
980 lua_getglobal(L, "table");
981 lua_getfield(L, -1, "insert");
982 int insertion_func = lua_gettop(L);
984 // Package them up for Lua
986 int new_table = lua_gettop(L);
987 std::list<std::string>::iterator i = mods_sorted.begin();
988 while(i != mods_sorted.end())
990 lua_pushvalue(L, insertion_func);
991 lua_pushvalue(L, new_table);
992 lua_pushstring(L, (*i).c_str());
993 if(lua_pcall(L, 2, 0, 0) != 0)
995 script_error(L, "error: %s", lua_tostring(L, -1));
1003 static int l_get_worldpath(lua_State *L)
1005 std::string worldpath = get_server(L)->getWorldPath();
1006 lua_pushstring(L, worldpath.c_str());
1010 // sound_play(spec, parameters)
1011 static int l_sound_play(lua_State *L)
1013 SimpleSoundSpec spec;
1014 read_soundspec(L, 1, spec);
1015 ServerSoundParams params;
1016 read_server_sound_params(L, 2, params);
1017 s32 handle = get_server(L)->playSound(spec, params);
1018 lua_pushinteger(L, handle);
1022 // sound_stop(handle)
1023 static int l_sound_stop(lua_State *L)
1025 int handle = luaL_checkinteger(L, 1);
1026 get_server(L)->stopSound(handle);
1030 // is_singleplayer()
1031 static int l_is_singleplayer(lua_State *L)
1033 lua_pushboolean(L, get_server(L)->isSingleplayer());
1037 // get_password_hash(name, raw_password)
1038 static int l_get_password_hash(lua_State *L)
1040 std::string name = luaL_checkstring(L, 1);
1041 std::string raw_password = luaL_checkstring(L, 2);
1042 std::string hash = translatePassword(name,
1043 narrow_to_wide(raw_password));
1044 lua_pushstring(L, hash.c_str());
1048 // notify_authentication_modified(name)
1049 static int l_notify_authentication_modified(lua_State *L)
1051 std::string name = "";
1052 if(lua_isstring(L, 1))
1053 name = lua_tostring(L, 1);
1054 get_server(L)->reportPrivsModified(name);
1058 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
1059 static int l_rollback_get_last_node_actor(lua_State *L)
1061 v3s16 p = read_v3s16(L, 1);
1062 int range = luaL_checknumber(L, 2);
1063 int seconds = luaL_checknumber(L, 3);
1064 Server *server = get_server(L);
1065 IRollbackManager *rollback = server->getRollbackManager();
1067 int act_seconds = 0;
1068 std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
1069 lua_pushstring(L, actor.c_str());
1070 push_v3s16(L, act_p);
1071 lua_pushnumber(L, act_seconds);
1075 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
1076 static int l_rollback_revert_actions_by(lua_State *L)
1078 std::string actor = luaL_checkstring(L, 1);
1079 int seconds = luaL_checknumber(L, 2);
1080 Server *server = get_server(L);
1081 IRollbackManager *rollback = server->getRollbackManager();
1082 std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
1083 std::list<std::string> log;
1084 bool success = server->rollbackRevertActions(actions, &log);
1085 // Push boolean result
1086 lua_pushboolean(L, success);
1087 // Get the table insert function and push the log table
1088 lua_getglobal(L, "table");
1089 lua_getfield(L, -1, "insert");
1090 int table_insert = lua_gettop(L);
1092 int table = lua_gettop(L);
1093 for(std::list<std::string>::const_iterator i = log.begin();
1094 i != log.end(); i++)
1096 lua_pushvalue(L, table_insert);
1097 lua_pushvalue(L, table);
1098 lua_pushstring(L, i->c_str());
1099 if(lua_pcall(L, 2, 0, 0))
1100 script_error(L, "error: %s", lua_tostring(L, -1));
1102 lua_remove(L, -2); // Remove table
1103 lua_remove(L, -2); // Remove insert
1107 static const struct luaL_Reg minetest_f [] = {
1110 {"request_shutdown", l_request_shutdown},
1111 {"get_server_status", l_get_server_status},
1112 {"register_item_raw", l_register_item_raw},
1113 {"register_alias_raw", l_register_alias_raw},
1114 {"register_craft", l_register_craft},
1115 {"register_biome", l_register_biome},
1116 {"register_biome_groups", l_register_biome_groups},
1117 {"register_ore", l_register_ore},
1118 {"setting_set", l_setting_set},
1119 {"setting_get", l_setting_get},
1120 {"setting_getbool", l_setting_getbool},
1121 {"setting_save",l_setting_save},
1122 {"chat_send_all", l_chat_send_all},
1123 {"chat_send_player", l_chat_send_player},
1124 {"get_player_privs", l_get_player_privs},
1125 {"get_ban_list", l_get_ban_list},
1126 {"get_ban_description", l_get_ban_description},
1127 {"ban_player", l_ban_player},
1128 {"unban_player_or_ip", l_unban_player_of_ip},
1129 {"get_inventory", l_get_inventory},
1130 {"create_detached_inventory_raw", l_create_detached_inventory_raw},
1131 {"show_formspec", l_show_formspec},
1132 {"get_dig_params", l_get_dig_params},
1133 {"get_hit_params", l_get_hit_params},
1134 {"get_current_modname", l_get_current_modname},
1135 {"get_modpath", l_get_modpath},
1136 {"get_modnames", l_get_modnames},
1137 {"get_worldpath", l_get_worldpath},
1138 {"sound_play", l_sound_play},
1139 {"sound_stop", l_sound_stop},
1140 {"is_singleplayer", l_is_singleplayer},
1141 {"get_password_hash", l_get_password_hash},
1142 {"notify_authentication_modified", l_notify_authentication_modified},
1143 {"get_craft_result", l_get_craft_result},
1144 {"get_craft_recipe", l_get_craft_recipe},
1145 {"get_all_craft_recipes", l_get_all_craft_recipes},
1146 {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
1147 {"rollback_revert_actions_by", l_rollback_revert_actions_by},
1148 {"add_particle", l_add_particle},
1149 {"add_particlespawner", l_add_particlespawner},
1150 {"delete_particlespawner", l_delete_particlespawner},
1156 Main export function
1159 void scriptapi_export(lua_State *L, Server *server)
1162 assert(lua_checkstack(L, 20));
1163 verbosestream<<"scriptapi_export()"<<std::endl;
1164 StackUnroller stack_unroller(L);
1166 // Store server as light userdata in registry
1167 lua_pushlightuserdata(L, server);
1168 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
1170 // Register global functions in table minetest
1172 luaL_register(L, NULL, minetest_f);
1173 lua_setglobal(L, "minetest");
1175 // Get the main minetest table
1176 lua_getglobal(L, "minetest");
1178 // Add tables to minetest
1180 lua_setfield(L, -2, "object_refs");
1182 lua_setfield(L, -2, "luaentities");
1184 // Register wrappers
1185 LuaItemStack::Register(L);
1186 InvRef::Register(L);
1187 NodeMetaRef::Register(L);
1188 NodeTimerRef::Register(L);
1189 ObjectRef::Register(L);
1190 EnvRef::Register(L);
1191 LuaPseudoRandom::Register(L);
1192 LuaPerlinNoise::Register(L);
1193 LuaPerlinNoiseMap::Register(L);