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, MODNAME_ALLOWED_CHARS)){
80 errorstream<<"Error loading mod \""<<modname
81 <<"\": modname does not follow naming conventions: "
82 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
89 success = script_load(L, scriptpath.c_str());
92 errorstream<<"Error loading mod \""<<modname
93 <<"\": "<<e.what()<<std::endl;
100 /*****************************************************************************/
102 /*****************************************************************************/
107 static void read_privileges(lua_State *L, int index,
108 std::set<std::string> &result)
114 while(lua_next(L, index) != 0){
115 // key at index -2 and value at index -1
116 std::string key = luaL_checkstring(L, -2);
117 bool value = lua_toboolean(L, -1);
120 // removes value, keeps key for next iteration
125 static void get_auth_handler(lua_State *L)
127 lua_getglobal(L, "minetest");
128 lua_getfield(L, -1, "registered_auth_handler");
129 if(lua_isnil(L, -1)){
131 lua_getfield(L, -1, "builtin_auth_handler");
133 if(lua_type(L, -1) != LUA_TTABLE)
134 throw LuaError(L, "Authentication handler table not valid");
137 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
138 std::string *dst_password, std::set<std::string> *dst_privs)
141 assert(lua_checkstack(L, 20));
142 StackUnroller stack_unroller(L);
145 lua_getfield(L, -1, "get_auth");
146 if(lua_type(L, -1) != LUA_TFUNCTION)
147 throw LuaError(L, "Authentication handler missing get_auth");
148 lua_pushstring(L, playername.c_str());
149 if(lua_pcall(L, 1, 1, 0))
150 script_error(L, "error: %s", lua_tostring(L, -1));
152 // nil = login not allowed
155 luaL_checktype(L, -1, LUA_TTABLE);
157 std::string password;
158 bool found = getstringfield(L, -1, "password", password);
160 throw LuaError(L, "Authentication handler didn't return password");
162 *dst_password = password;
164 lua_getfield(L, -1, "privileges");
165 if(!lua_istable(L, -1))
167 "Authentication handler didn't return privilege table");
169 read_privileges(L, -1, *dst_privs);
175 void scriptapi_create_auth(lua_State *L, const std::string &playername,
176 const std::string &password)
179 assert(lua_checkstack(L, 20));
180 StackUnroller stack_unroller(L);
183 lua_getfield(L, -1, "create_auth");
184 if(lua_type(L, -1) != LUA_TFUNCTION)
185 throw LuaError(L, "Authentication handler missing create_auth");
186 lua_pushstring(L, playername.c_str());
187 lua_pushstring(L, password.c_str());
188 if(lua_pcall(L, 2, 0, 0))
189 script_error(L, "error: %s", lua_tostring(L, -1));
192 bool scriptapi_set_password(lua_State *L, const std::string &playername,
193 const std::string &password)
196 assert(lua_checkstack(L, 20));
197 StackUnroller stack_unroller(L);
200 lua_getfield(L, -1, "set_password");
201 if(lua_type(L, -1) != LUA_TFUNCTION)
202 throw LuaError(L, "Authentication handler missing set_password");
203 lua_pushstring(L, playername.c_str());
204 lua_pushstring(L, password.c_str());
205 if(lua_pcall(L, 2, 1, 0))
206 script_error(L, "error: %s", lua_tostring(L, -1));
207 return lua_toboolean(L, -1);
210 /*****************************************************************************/
212 /*****************************************************************************/
216 void read_groups(lua_State *L, int index,
217 std::map<std::string, int> &result)
219 if (!lua_istable(L,index))
225 while(lua_next(L, index) != 0){
226 // key at index -2 and value at index -1
227 std::string name = luaL_checkstring(L, -2);
228 int rating = luaL_checkinteger(L, -1);
229 result[name] = rating;
230 // removes value, keeps key for next iteration
235 struct EnumString es_BiomeTerrainType[] =
237 {BIOME_TERRAIN_NORMAL, "normal"},
238 {BIOME_TERRAIN_LIQUID, "liquid"},
239 {BIOME_TERRAIN_NETHER, "nether"},
240 {BIOME_TERRAIN_AETHER, "aether"},
241 {BIOME_TERRAIN_FLAT, "flat"},
245 struct EnumString es_OreType[] =
247 {ORE_SCATTER, "scatter"},
248 {ORE_SHEET, "sheet"},
249 {ORE_CLAYLIKE, "claylike"},
253 /*****************************************************************************/
255 /*****************************************************************************/
260 static void set_dig_params(lua_State *L, int table,
261 const DigParams ¶ms)
263 setboolfield(L, table, "diggable", params.diggable);
264 setfloatfield(L, table, "time", params.time);
265 setintfield(L, table, "wear", params.wear);
268 static void push_dig_params(lua_State *L,
269 const DigParams ¶ms)
272 set_dig_params(L, -1, params);
279 static void set_hit_params(lua_State *L, int table,
280 const HitParams ¶ms)
282 setintfield(L, table, "hp", params.hp);
283 setintfield(L, table, "wear", params.wear);
286 static void push_hit_params(lua_State *L,
287 const HitParams ¶ms)
290 set_hit_params(L, -1, params);
297 static void read_server_sound_params(lua_State *L, int index,
298 ServerSoundParams ¶ms)
301 index = lua_gettop(L) + 1 + index;
303 params = ServerSoundParams();
304 if(lua_istable(L, index)){
305 getfloatfield(L, index, "gain", params.gain);
306 getstringfield(L, index, "to_player", params.to_player);
307 lua_getfield(L, index, "pos");
308 if(!lua_isnil(L, -1)){
309 v3f p = read_v3f(L, -1)*BS;
311 params.type = ServerSoundParams::SSP_POSITIONAL;
314 lua_getfield(L, index, "object");
315 if(!lua_isnil(L, -1)){
316 ObjectRef *ref = ObjectRef::checkobject(L, -1);
317 ServerActiveObject *sao = ObjectRef::getobject(ref);
319 params.object = sao->getId();
320 params.type = ServerSoundParams::SSP_OBJECT;
324 params.max_hear_distance = BS*getfloatfield_default(L, index,
325 "max_hear_distance", params.max_hear_distance/BS);
326 getboolfield(L, index, "loop", params.loop);
330 /*****************************************************************************/
332 /*****************************************************************************/
334 // Push the list of callbacks (a lua table).
335 // Then push nargs arguments.
336 // Then call this function, which
337 // - runs the callbacks
338 // - removes the table and arguments from the lua stack
339 // - pushes the return value, computed depending on mode
340 void scriptapi_run_callbacks(lua_State *L, int nargs,
341 RunCallbacksMode mode)
343 // Insert the return value into the lua stack, below the table
344 assert(lua_gettop(L) >= nargs + 1);
346 lua_insert(L, -(nargs + 1) - 1);
347 // Stack now looks like this:
348 // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
350 int rv = lua_gettop(L) - nargs - 1;
354 luaL_checktype(L, table, LUA_TTABLE);
358 bool first_loop = true;
359 while(lua_next(L, table) != 0){
360 // key at index -2 and value at index -1
361 luaL_checktype(L, -1, LUA_TFUNCTION);
363 for(int i = 0; i < nargs; i++)
364 lua_pushvalue(L, arg+i);
365 if(lua_pcall(L, nargs, 1, 0))
366 script_error(L, "error: %s", lua_tostring(L, -1));
368 // Move return value to designated space in stack
371 // Result of first callback is always moved
375 // Otherwise, what happens depends on the mode
376 if(mode == RUN_CALLBACKS_MODE_FIRST)
378 else if(mode == RUN_CALLBACKS_MODE_LAST)
380 else if(mode == RUN_CALLBACKS_MODE_AND ||
381 mode == RUN_CALLBACKS_MODE_AND_SC){
382 if((bool)lua_toboolean(L, rv) == true &&
383 (bool)lua_toboolean(L, -1) == false)
388 else if(mode == RUN_CALLBACKS_MODE_OR ||
389 mode == RUN_CALLBACKS_MODE_OR_SC){
390 if((bool)lua_toboolean(L, rv) == false &&
391 (bool)lua_toboolean(L, -1) == true)
400 // Handle short circuit modes
401 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
402 (bool)lua_toboolean(L, rv) == false)
404 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
405 (bool)lua_toboolean(L, rv) == true)
408 // value removed, keep key for next iteration
411 // Remove stuff from stack, leaving only the return value
414 // Fix return value in case no callbacks were called
416 if(mode == RUN_CALLBACKS_MODE_AND ||
417 mode == RUN_CALLBACKS_MODE_AND_SC){
419 lua_pushboolean(L, true);
421 else if(mode == RUN_CALLBACKS_MODE_OR ||
422 mode == RUN_CALLBACKS_MODE_OR_SC){
424 lua_pushboolean(L, false);
429 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
430 const std::string &message)
433 assert(lua_checkstack(L, 20));
434 StackUnroller stack_unroller(L);
436 // Get minetest.registered_on_chat_messages
437 lua_getglobal(L, "minetest");
438 lua_getfield(L, -1, "registered_on_chat_messages");
440 lua_pushstring(L, name.c_str());
441 lua_pushstring(L, message.c_str());
442 scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
443 bool ate = lua_toboolean(L, -1);
447 void scriptapi_on_shutdown(lua_State *L)
450 assert(lua_checkstack(L, 20));
451 StackUnroller stack_unroller(L);
453 // Get registered shutdown hooks
454 lua_getglobal(L, "minetest");
455 lua_getfield(L, -1, "registered_on_shutdown");
457 scriptapi_run_callbacks(L, 0, RUN_CALLBACKS_MODE_FIRST);
460 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
463 assert(lua_checkstack(L, 20));
464 StackUnroller stack_unroller(L);
466 // Get minetest.registered_on_newplayers
467 lua_getglobal(L, "minetest");
468 lua_getfield(L, -1, "registered_on_newplayers");
470 objectref_get_or_create(L, player);
471 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
474 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
477 assert(lua_checkstack(L, 20));
478 StackUnroller stack_unroller(L);
480 // Get minetest.registered_on_dieplayers
481 lua_getglobal(L, "minetest");
482 lua_getfield(L, -1, "registered_on_dieplayers");
484 objectref_get_or_create(L, player);
485 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
488 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
491 assert(lua_checkstack(L, 20));
492 StackUnroller stack_unroller(L);
494 // Get minetest.registered_on_respawnplayers
495 lua_getglobal(L, "minetest");
496 lua_getfield(L, -1, "registered_on_respawnplayers");
498 objectref_get_or_create(L, player);
499 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
500 bool positioning_handled_by_some = lua_toboolean(L, -1);
501 return positioning_handled_by_some;
504 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
507 assert(lua_checkstack(L, 20));
508 StackUnroller stack_unroller(L);
510 // Get minetest.registered_on_joinplayers
511 lua_getglobal(L, "minetest");
512 lua_getfield(L, -1, "registered_on_joinplayers");
514 objectref_get_or_create(L, player);
515 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
518 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
521 assert(lua_checkstack(L, 20));
522 StackUnroller stack_unroller(L);
524 // Get minetest.registered_on_leaveplayers
525 lua_getglobal(L, "minetest");
526 lua_getfield(L, -1, "registered_on_leaveplayers");
528 objectref_get_or_create(L, player);
529 scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
535 void scriptapi_on_player_receive_fields(lua_State *L,
536 ServerActiveObject *player,
537 const std::string &formname,
538 const std::map<std::string, std::string> &fields)
541 assert(lua_checkstack(L, 20));
542 StackUnroller stack_unroller(L);
544 // Get minetest.registered_on_chat_messages
545 lua_getglobal(L, "minetest");
546 lua_getfield(L, -1, "registered_on_player_receive_fields");
549 objectref_get_or_create(L, player);
551 lua_pushstring(L, formname.c_str());
554 for(std::map<std::string, std::string>::const_iterator
555 i = fields.begin(); i != fields.end(); i++){
556 const std::string &name = i->first;
557 const std::string &value = i->second;
558 lua_pushstring(L, name.c_str());
559 lua_pushlstring(L, value.c_str(), value.size());
562 scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
564 /*****************************************************************************/
566 /*****************************************************************************/
569 // Writes a line to dstream
570 static int l_debug(lua_State *L)
572 std::string text = lua_tostring(L, 1);
573 dstream << text << std::endl;
577 // log([level,] text)
578 // Writes a line to the logger.
579 // The one-argument version logs to infostream.
580 // The two-argument version accept a log level: error, action, info, or verbose.
581 static int l_log(lua_State *L)
584 LogMessageLevel level = LMT_INFO;
587 text = lua_tostring(L, 1);
591 std::string levelname = luaL_checkstring(L, 1);
592 text = luaL_checkstring(L, 2);
593 if(levelname == "error")
595 else if(levelname == "action")
597 else if(levelname == "verbose")
600 log_printline(level, text);
604 // request_shutdown()
605 static int l_request_shutdown(lua_State *L)
607 get_server(L)->requestShutdown();
611 // get_server_status()
612 static int l_get_server_status(lua_State *L)
614 lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
619 // register_biome({lots of stuff})
620 static int l_register_biome(lua_State *L)
623 luaL_checktype(L, index, LUA_TTABLE);
625 BiomeDefManager *bmgr = get_server(L)->getEmergeManager()->biomedef;
627 verbosestream << "register_biome: BiomeDefManager not active" << std::endl;
631 enum BiomeTerrainType terrain = (BiomeTerrainType)getenumfield(L, index,
632 "terrain_type", es_BiomeTerrainType, BIOME_TERRAIN_NORMAL);
633 Biome *b = bmgr->createBiome(terrain);
635 b->name = getstringfield_default(L, index, "name", "");
636 b->top_nodename = getstringfield_default(L, index, "top_node", "");
637 b->top_depth = getintfield_default(L, index, "top_depth", 0);
638 b->filler_nodename = getstringfield_default(L, index, "filler_node", "");
639 b->filler_height = getintfield_default(L, index, "filler_height", 0);
640 b->height_min = getintfield_default(L, index, "height_min", 0);
641 b->height_max = getintfield_default(L, index, "height_max", 0);
642 b->heat_point = getfloatfield_default(L, index, "heat_point", 0.);
643 b->humidity_point = getfloatfield_default(L, index, "humidity_point", 0.);
645 b->flags = 0; //reserved
646 b->c_top = CONTENT_IGNORE;
647 b->c_filler = CONTENT_IGNORE;
650 verbosestream << "register_biome: " << b->name << std::endl;
655 static int l_register_ore(lua_State *L)
658 luaL_checktype(L, index, LUA_TTABLE);
660 EmergeManager *emerge = get_server(L)->getEmergeManager();
662 enum OreType oretype = (OreType)getenumfield(L, index,
663 "ore_type", es_OreType, ORE_SCATTER);
664 Ore *ore = createOre(oretype);
666 errorstream << "register_ore: ore_type "
667 << oretype << " not implemented";
671 ore->ore_name = getstringfield_default(L, index, "ore", "");
672 ore->ore_param2 = (u8)getintfield_default(L, index, "ore_param2", 0);
673 ore->wherein_name = getstringfield_default(L, index, "wherein", "");
674 ore->clust_scarcity = getintfield_default(L, index, "clust_scarcity", 1);
675 ore->clust_num_ores = getintfield_default(L, index, "clust_num_ores", 1);
676 ore->clust_size = getintfield_default(L, index, "clust_size", 0);
677 ore->height_min = getintfield_default(L, index, "height_min", 0);
678 ore->height_max = getintfield_default(L, index, "height_max", 0);
679 ore->flags = getflagsfield(L, index, "flags", flagdesc_ore);
680 ore->nthresh = getfloatfield_default(L, index, "noise_threshhold", 0.);
682 lua_getfield(L, index, "noise_params");
683 ore->np = read_noiseparams(L, -1);
688 if (ore->clust_scarcity <= 0 || ore->clust_num_ores <= 0) {
689 errorstream << "register_ore: clust_scarcity and clust_num_ores"
690 " must be greater than 0" << std::endl;
695 emerge->ores.push_back(ore);
697 verbosestream << "register_ore: ore '" << ore->ore_name
698 << "' registered" << std::endl;
703 // setting_set(name, value)
704 static int l_setting_set(lua_State *L)
706 const char *name = luaL_checkstring(L, 1);
707 const char *value = luaL_checkstring(L, 2);
708 g_settings->set(name, value);
713 static int l_setting_get(lua_State *L)
715 const char *name = luaL_checkstring(L, 1);
717 std::string value = g_settings->get(name);
718 lua_pushstring(L, value.c_str());
719 } catch(SettingNotFoundException &e){
725 // setting_getbool(name)
726 static int l_setting_getbool(lua_State *L)
728 const char *name = luaL_checkstring(L, 1);
730 bool value = g_settings->getBool(name);
731 lua_pushboolean(L, value);
732 } catch(SettingNotFoundException &e){
739 static int l_setting_save(lua_State *L)
741 get_server(L)->saveConfig();
745 // chat_send_all(text)
746 static int l_chat_send_all(lua_State *L)
748 const char *text = luaL_checkstring(L, 1);
749 // Get server from registry
750 Server *server = get_server(L);
752 server->notifyPlayers(narrow_to_wide(text));
756 // chat_send_player(name, text, prepend)
757 static int l_chat_send_player(lua_State *L)
759 const char *name = luaL_checkstring(L, 1);
760 const char *text = luaL_checkstring(L, 2);
762 if (lua_isboolean(L, 3))
763 prepend = lua_toboolean(L, 3);
764 // Get server from registry
765 Server *server = get_server(L);
767 server->notifyPlayer(name, narrow_to_wide(text), prepend);
771 // get_player_privs(name, text)
772 static int l_get_player_privs(lua_State *L)
774 const char *name = luaL_checkstring(L, 1);
775 // Get server from registry
776 Server *server = get_server(L);
779 int table = lua_gettop(L);
780 std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
781 for(std::set<std::string>::const_iterator
782 i = privs_s.begin(); i != privs_s.end(); i++){
783 lua_pushboolean(L, true);
784 lua_setfield(L, table, i->c_str());
786 lua_pushvalue(L, table);
791 static int l_get_player_ip(lua_State *L)
793 const char * name = luaL_checkstring(L, 1);
794 Player *player = get_env(L)->getPlayer(name);
797 lua_pushnil(L); // no such player
802 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
803 std::string ip_str = addr.serializeString();
804 lua_pushstring(L, ip_str.c_str());
807 catch(con::PeerNotFoundException) // unlikely
809 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
810 lua_pushnil(L); // error
816 static int l_get_ban_list(lua_State *L)
818 lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
822 // get_ban_description()
823 static int l_get_ban_description(lua_State *L)
825 const char * ip_or_name = luaL_checkstring(L, 1);
826 lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
831 static int l_ban_player(lua_State *L)
833 const char * name = luaL_checkstring(L, 1);
834 Player *player = get_env(L)->getPlayer(name);
837 lua_pushboolean(L, false); // no such player
842 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
843 std::string ip_str = addr.serializeString();
844 get_server(L)->setIpBanned(ip_str, name);
846 catch(con::PeerNotFoundException) // unlikely
848 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
849 lua_pushboolean(L, false); // error
852 lua_pushboolean(L, true);
856 // unban_player_or_ip()
857 static int l_unban_player_of_ip(lua_State *L)
859 const char * ip_or_name = luaL_checkstring(L, 1);
860 get_server(L)->unsetIpBanned(ip_or_name);
861 lua_pushboolean(L, true);
865 // show_formspec(playername,formname,formspec)
866 static int l_show_formspec(lua_State *L)
868 const char *playername = luaL_checkstring(L, 1);
869 const char *formname = luaL_checkstring(L, 2);
870 const char *formspec = luaL_checkstring(L, 3);
872 if(get_server(L)->showFormspec(playername,formspec,formname))
874 lua_pushboolean(L, true);
876 lua_pushboolean(L, false);
881 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
882 static int l_get_dig_params(lua_State *L)
884 std::map<std::string, int> groups;
885 read_groups(L, 1, groups);
886 ToolCapabilities tp = read_tool_capabilities(L, 2);
887 if(lua_isnoneornil(L, 3))
888 push_dig_params(L, getDigParams(groups, &tp));
890 push_dig_params(L, getDigParams(groups, &tp,
891 luaL_checknumber(L, 3)));
895 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
896 static int l_get_hit_params(lua_State *L)
898 std::map<std::string, int> groups;
899 read_groups(L, 1, groups);
900 ToolCapabilities tp = read_tool_capabilities(L, 2);
901 if(lua_isnoneornil(L, 3))
902 push_hit_params(L, getHitParams(groups, &tp));
904 push_hit_params(L, getHitParams(groups, &tp,
905 luaL_checknumber(L, 3)));
909 // get_current_modname()
910 static int l_get_current_modname(lua_State *L)
912 lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
916 // get_modpath(modname)
917 static int l_get_modpath(lua_State *L)
919 std::string modname = luaL_checkstring(L, 1);
921 if(modname == "__builtin"){
922 std::string path = get_server(L)->getBuiltinLuaPath();
923 lua_pushstring(L, path.c_str());
926 const ModSpec *mod = get_server(L)->getModSpec(modname);
931 lua_pushstring(L, mod->path.c_str());
936 // the returned list is sorted alphabetically for you
937 static int l_get_modnames(lua_State *L)
939 // Get a list of mods
940 std::list<std::string> mods_unsorted, mods_sorted;
941 get_server(L)->getModNames(mods_unsorted);
943 // Take unsorted items from mods_unsorted and sort them into
944 // mods_sorted; not great performance but the number of mods on a
945 // server will likely be small.
946 for(std::list<std::string>::iterator i = mods_unsorted.begin();
947 i != mods_unsorted.end(); ++i)
950 for(std::list<std::string>::iterator x = mods_sorted.begin();
951 x != mods_sorted.end(); ++x)
953 // I doubt anybody using Minetest will be using
954 // anything not ASCII based :)
955 if((*i).compare(*x) <= 0)
957 mods_sorted.insert(x, *i);
963 mods_sorted.push_back(*i);
966 // Get the table insertion function from Lua.
967 lua_getglobal(L, "table");
968 lua_getfield(L, -1, "insert");
969 int insertion_func = lua_gettop(L);
971 // Package them up for Lua
973 int new_table = lua_gettop(L);
974 std::list<std::string>::iterator i = mods_sorted.begin();
975 while(i != mods_sorted.end())
977 lua_pushvalue(L, insertion_func);
978 lua_pushvalue(L, new_table);
979 lua_pushstring(L, (*i).c_str());
980 if(lua_pcall(L, 2, 0, 0) != 0)
982 script_error(L, "error: %s", lua_tostring(L, -1));
990 static int l_get_worldpath(lua_State *L)
992 std::string worldpath = get_server(L)->getWorldPath();
993 lua_pushstring(L, worldpath.c_str());
997 // sound_play(spec, parameters)
998 static int l_sound_play(lua_State *L)
1000 SimpleSoundSpec spec;
1001 read_soundspec(L, 1, spec);
1002 ServerSoundParams params;
1003 read_server_sound_params(L, 2, params);
1004 s32 handle = get_server(L)->playSound(spec, params);
1005 lua_pushinteger(L, handle);
1009 // sound_stop(handle)
1010 static int l_sound_stop(lua_State *L)
1012 int handle = luaL_checkinteger(L, 1);
1013 get_server(L)->stopSound(handle);
1017 // is_singleplayer()
1018 static int l_is_singleplayer(lua_State *L)
1020 lua_pushboolean(L, get_server(L)->isSingleplayer());
1024 // get_password_hash(name, raw_password)
1025 static int l_get_password_hash(lua_State *L)
1027 std::string name = luaL_checkstring(L, 1);
1028 std::string raw_password = luaL_checkstring(L, 2);
1029 std::string hash = translatePassword(name,
1030 narrow_to_wide(raw_password));
1031 lua_pushstring(L, hash.c_str());
1035 // notify_authentication_modified(name)
1036 static int l_notify_authentication_modified(lua_State *L)
1038 std::string name = "";
1039 if(lua_isstring(L, 1))
1040 name = lua_tostring(L, 1);
1041 get_server(L)->reportPrivsModified(name);
1045 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
1046 static int l_rollback_get_last_node_actor(lua_State *L)
1048 v3s16 p = read_v3s16(L, 1);
1049 int range = luaL_checknumber(L, 2);
1050 int seconds = luaL_checknumber(L, 3);
1051 Server *server = get_server(L);
1052 IRollbackManager *rollback = server->getRollbackManager();
1054 int act_seconds = 0;
1055 std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
1056 lua_pushstring(L, actor.c_str());
1057 push_v3s16(L, act_p);
1058 lua_pushnumber(L, act_seconds);
1062 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
1063 static int l_rollback_revert_actions_by(lua_State *L)
1065 std::string actor = luaL_checkstring(L, 1);
1066 int seconds = luaL_checknumber(L, 2);
1067 Server *server = get_server(L);
1068 IRollbackManager *rollback = server->getRollbackManager();
1069 std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
1070 std::list<std::string> log;
1071 bool success = server->rollbackRevertActions(actions, &log);
1072 // Push boolean result
1073 lua_pushboolean(L, success);
1074 // Get the table insert function and push the log table
1075 lua_getglobal(L, "table");
1076 lua_getfield(L, -1, "insert");
1077 int table_insert = lua_gettop(L);
1079 int table = lua_gettop(L);
1080 for(std::list<std::string>::const_iterator i = log.begin();
1081 i != log.end(); i++)
1083 lua_pushvalue(L, table_insert);
1084 lua_pushvalue(L, table);
1085 lua_pushstring(L, i->c_str());
1086 if(lua_pcall(L, 2, 0, 0))
1087 script_error(L, "error: %s", lua_tostring(L, -1));
1089 lua_remove(L, -2); // Remove table
1090 lua_remove(L, -2); // Remove insert
1094 static const struct luaL_Reg minetest_f [] = {
1097 {"request_shutdown", l_request_shutdown},
1098 {"get_server_status", l_get_server_status},
1099 {"register_item_raw", l_register_item_raw},
1100 {"register_alias_raw", l_register_alias_raw},
1101 {"register_craft", l_register_craft},
1102 {"register_biome", l_register_biome},
1103 {"register_ore", l_register_ore},
1104 {"setting_set", l_setting_set},
1105 {"setting_get", l_setting_get},
1106 {"setting_getbool", l_setting_getbool},
1107 {"setting_save",l_setting_save},
1108 {"chat_send_all", l_chat_send_all},
1109 {"chat_send_player", l_chat_send_player},
1110 {"get_player_privs", l_get_player_privs},
1111 {"get_player_ip", l_get_player_ip},
1112 {"get_ban_list", l_get_ban_list},
1113 {"get_ban_description", l_get_ban_description},
1114 {"ban_player", l_ban_player},
1115 {"unban_player_or_ip", l_unban_player_of_ip},
1116 {"get_inventory", l_get_inventory},
1117 {"create_detached_inventory_raw", l_create_detached_inventory_raw},
1118 {"show_formspec", l_show_formspec},
1119 {"get_dig_params", l_get_dig_params},
1120 {"get_hit_params", l_get_hit_params},
1121 {"get_current_modname", l_get_current_modname},
1122 {"get_modpath", l_get_modpath},
1123 {"get_modnames", l_get_modnames},
1124 {"get_worldpath", l_get_worldpath},
1125 {"sound_play", l_sound_play},
1126 {"sound_stop", l_sound_stop},
1127 {"is_singleplayer", l_is_singleplayer},
1128 {"get_password_hash", l_get_password_hash},
1129 {"notify_authentication_modified", l_notify_authentication_modified},
1130 {"get_craft_result", l_get_craft_result},
1131 {"get_craft_recipe", l_get_craft_recipe},
1132 {"get_all_craft_recipes", l_get_all_craft_recipes},
1133 {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
1134 {"rollback_revert_actions_by", l_rollback_revert_actions_by},
1135 {"add_particle", l_add_particle},
1136 {"add_particlespawner", l_add_particlespawner},
1137 {"delete_particlespawner", l_delete_particlespawner},
1143 Main export function
1146 void scriptapi_export(lua_State *L, Server *server)
1149 assert(lua_checkstack(L, 20));
1150 verbosestream<<"scriptapi_export()"<<std::endl;
1151 StackUnroller stack_unroller(L);
1153 // Store server as light userdata in registry
1154 lua_pushlightuserdata(L, server);
1155 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
1157 // Register global functions in table minetest
1159 luaL_register(L, NULL, minetest_f);
1160 lua_setglobal(L, "minetest");
1162 // Get the main minetest table
1163 lua_getglobal(L, "minetest");
1165 // Add tables to minetest
1167 lua_setfield(L, -2, "object_refs");
1169 lua_setfield(L, -2, "luaentities");
1171 // Register wrappers
1172 LuaItemStack::Register(L);
1173 InvRef::Register(L);
1174 NodeMetaRef::Register(L);
1175 NodeTimerRef::Register(L);
1176 ObjectRef::Register(L);
1177 EnvRef::Register(L);
1178 LuaPseudoRandom::Register(L);
1179 LuaPerlinNoise::Register(L);
1180 LuaPerlinNoiseMap::Register(L);