Use "core" namespace internally

This commit is contained in:
ShadowNinja 2014-04-27 21:02:48 -04:00
parent 1cd512913e
commit c4359ff65c
45 changed files with 812 additions and 843 deletions

@ -1,6 +1,5 @@
engine.log("info", "Initializing Asynchronous environment")
local core = engine or minetest core.log("info", "Initializing Asynchronous environment")
function core.job_processor(serialized_func, serialized_param) function core.job_processor(serialized_func, serialized_param)
local func = loadstring(serialized_func) local func = loadstring(serialized_func)

@ -1,6 +1,4 @@
local core = engine or minetest
core.async_jobs = {} core.async_jobs = {}
local function handle_job(jobid, serialized_retval) local function handle_job(jobid, serialized_retval)
@ -10,14 +8,14 @@ local function handle_job(jobid, serialized_retval)
core.async_jobs[jobid] = nil core.async_jobs[jobid] = nil
end end
if engine ~= nil then if core.register_globalstep then
core.async_event_handler = handle_job core.register_globalstep(function(dtime)
else
minetest.register_globalstep(function(dtime)
for i, job in ipairs(core.get_finished_jobs()) do for i, job in ipairs(core.get_finished_jobs()) do
handle_job(job.jobid, job.retval) handle_job(job.jobid, job.retval)
end end
end) end)
else
core.async_event_handler = handle_job
end end
function core.handle_async(func, parameter, callback) function core.handle_async(func, parameter, callback)

@ -173,8 +173,7 @@ function cleanup_path(temppath)
return temppath return temppath
end end
local tbl = engine or minetest function core.formspec_escape(text)
function tbl.formspec_escape(text)
if text ~= nil then if text ~= nil then
text = string.gsub(text,"\\","\\\\") text = string.gsub(text,"\\","\\\\")
text = string.gsub(text,"%]","\\]") text = string.gsub(text,"%]","\\]")
@ -186,7 +185,7 @@ function tbl.formspec_escape(text)
end end
function tbl.splittext(text,charlimit) function core.splittext(text,charlimit)
local retval = {} local retval = {}
local current_idx = 1 local current_idx = 1
@ -243,33 +242,33 @@ end
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
if minetest then if INIT == "game" then
local dirs1 = {9, 18, 7, 12} local dirs1 = {9, 18, 7, 12}
local dirs2 = {20, 23, 22, 21} local dirs2 = {20, 23, 22, 21}
function minetest.rotate_and_place(itemstack, placer, pointed_thing, function core.rotate_and_place(itemstack, placer, pointed_thing,
infinitestacks, orient_flags) infinitestacks, orient_flags)
orient_flags = orient_flags or {} orient_flags = orient_flags or {}
local unode = minetest.get_node_or_nil(pointed_thing.under) local unode = core.get_node_or_nil(pointed_thing.under)
if not unode then if not unode then
return return
end end
local undef = minetest.registered_nodes[unode.name] local undef = core.registered_nodes[unode.name]
if undef and undef.on_rightclick then if undef and undef.on_rightclick then
undef.on_rightclick(pointed_thing.under, unode, placer, undef.on_rightclick(pointed_thing.under, unode, placer,
itemstack, pointed_thing) itemstack, pointed_thing)
return return
end end
local pitch = placer:get_look_pitch() local pitch = placer:get_look_pitch()
local fdir = minetest.dir_to_facedir(placer:get_look_dir()) local fdir = core.dir_to_facedir(placer:get_look_dir())
local wield_name = itemstack:get_name() local wield_name = itemstack:get_name()
local above = pointed_thing.above local above = pointed_thing.above
local under = pointed_thing.under local under = pointed_thing.under
local iswall = (above.y == under.y) local iswall = (above.y == under.y)
local isceiling = not iswall and (above.y < under.y) local isceiling = not iswall and (above.y < under.y)
local anode = minetest.get_node_or_nil(above) local anode = core.get_node_or_nil(above)
if not anode then if not anode then
return return
end end
@ -282,13 +281,13 @@ if minetest then
iswall = false iswall = false
end end
if minetest.is_protected(pos, placer:get_player_name()) then if core.is_protected(pos, placer:get_player_name()) then
minetest.record_protection_violation(pos, core.record_protection_violation(pos,
placer:get_player_name()) placer:get_player_name())
return return
end end
local ndef = minetest.registered_nodes[node.name] local ndef = core.registered_nodes[node.name]
if not ndef or not ndef.buildable_to then if not ndef or not ndef.buildable_to then
return return
end end
@ -307,22 +306,22 @@ if minetest then
end end
if iswall then if iswall then
minetest.set_node(pos, {name = wield_name, core.set_node(pos, {name = wield_name,
param2 = dirs1[fdir+1]}) param2 = dirs1[fdir+1]})
elseif isceiling then elseif isceiling then
if orient_flags.force_facedir then if orient_flags.force_facedir then
minetest.set_node(pos, {name = wield_name, core.set_node(pos, {name = wield_name,
param2 = 20}) param2 = 20})
else else
minetest.set_node(pos, {name = wield_name, core.set_node(pos, {name = wield_name,
param2 = dirs2[fdir+1]}) param2 = dirs2[fdir+1]})
end end
else -- place right side up else -- place right side up
if orient_flags.force_facedir then if orient_flags.force_facedir then
minetest.set_node(pos, {name = wield_name, core.set_node(pos, {name = wield_name,
param2 = 0}) param2 = 0})
else else
minetest.set_node(pos, {name = wield_name, core.set_node(pos, {name = wield_name,
param2 = fdir}) param2 = fdir})
end end
end end
@ -340,16 +339,16 @@ if minetest then
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
minetest.rotate_node = function(itemstack, placer, pointed_thing) core.rotate_node = function(itemstack, placer, pointed_thing)
minetest.rotate_and_place(itemstack, placer, pointed_thing, core.rotate_and_place(itemstack, placer, pointed_thing,
minetest.setting_getbool("creative_mode"), core.setting_getbool("creative_mode"),
{invert_wall = placer:get_player_control().sneak}) {invert_wall = placer:get_player_control().sneak})
return itemstack return itemstack
end end
end end
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
function tbl.explode_table_event(evt) function core.explode_table_event(evt)
if evt ~= nil then if evt ~= nil then
local parts = evt:split(":") local parts = evt:split(":")
if #parts == 3 then if #parts == 3 then
@ -365,7 +364,7 @@ function tbl.explode_table_event(evt)
end end
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
function tbl.explode_textlist_event(evt) function core.explode_textlist_event(evt)
if evt ~= nil then if evt ~= nil then
local parts = evt:split(":") local parts = evt:split(":")
if #parts == 2 then if #parts == 2 then
@ -379,11 +378,15 @@ function tbl.explode_textlist_event(evt)
return {type="INV", index=0} return {type="INV", index=0}
end end
function core.pos_to_string(pos)
return "(" .. pos.x .. "," .. pos.y .. "," .. pos.z .. ")"
end
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
-- mainmenu only functions -- mainmenu only functions
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
if engine ~= nil then if INIT == "mainmenu" then
engine.get_game = function(index) function core.get_game(index)
local games = game.get_games() local games = game.get_games()
if index > 0 and index <= #games then if index > 0 and index <= #games then
@ -394,7 +397,7 @@ if engine ~= nil then
end end
function fgettext(text, ...) function fgettext(text, ...)
text = engine.gettext(text) text = core.gettext(text)
local arg = {n=select('#', ...), ...} local arg = {n=select('#', ...), ...}
if arg.n >= 1 then if arg.n >= 1 then
-- Insert positional parameters ($1, $2, ...) -- Insert positional parameters ($1, $2, ...)
@ -413,16 +416,7 @@ if engine ~= nil then
end end
text = result text = result
end end
return engine.formspec_escape(text) return core.formspec_escape(text)
end
end
--------------------------------------------------------------------------------
-- core only fct
--------------------------------------------------------------------------------
if minetest ~= nil then
--------------------------------------------------------------------------------
function minetest.pos_to_string(pos)
return "(" .. pos.x .. "," .. pos.y .. "," .. pos.z .. ")"
end end
end end

@ -14,7 +14,7 @@
local no_identity = { number=1, boolean=1, string=1, ['nil']=1 } local no_identity = { number=1, boolean=1, string=1, ['nil']=1 }
function minetest.serialize(x) function core.serialize(x)
local gensym_max = 0 -- index of the gensym() symbol generator local gensym_max = 0 -- index of the gensym() symbol generator
local seen_once = { } -- element->true set of elements seen exactly once in the table local seen_once = { } -- element->true set of elements seen exactly once in the table
@ -188,13 +188,13 @@ local function stringtotable(sdata, safe)
return f() return f()
end end
function minetest.deserialize(sdata, safe) function core.deserialize(sdata, safe)
local table = {} local table = {}
local okay, results = pcall(stringtotable, sdata, safe) local okay, results = pcall(stringtotable, sdata, safe)
if okay then if okay then
return results return results
end end
minetest.log('error', 'minetest.deserialize(): '.. results) core.log('error', 'core.deserialize(): '.. results)
return nil return nil
end end
@ -207,14 +207,14 @@ local function unit_test()
end end
unittest_input = {cat={sound="nyan", speed=400}, dog={sound="woof"}} unittest_input = {cat={sound="nyan", speed=400}, dog={sound="woof"}}
unittest_output = minetest.deserialize(minetest.serialize(unittest_input)) unittest_output = core.deserialize(core.serialize(unittest_input))
unitTest("test 1a", unittest_input.cat.sound == unittest_output.cat.sound) unitTest("test 1a", unittest_input.cat.sound == unittest_output.cat.sound)
unitTest("test 1b", unittest_input.cat.speed == unittest_output.cat.speed) unitTest("test 1b", unittest_input.cat.speed == unittest_output.cat.speed)
unitTest("test 1c", unittest_input.dog.sound == unittest_output.dog.sound) unitTest("test 1c", unittest_input.dog.sound == unittest_output.dog.sound)
unittest_input = {escapechars="\n\r\t\v\\\"\'", noneuropean="θשׁ٩∂"} unittest_input = {escapechars="\n\r\t\v\\\"\'", noneuropean="θשׁ٩∂"}
unittest_output = minetest.deserialize(minetest.serialize(unittest_input)) unittest_output = core.deserialize(core.serialize(unittest_input))
unitTest("test 3a", unittest_input.escapechars == unittest_output.escapechars) unitTest("test 3a", unittest_input.escapechars == unittest_output.escapechars)
unitTest("test 3b", unittest_input.noneuropean == unittest_output.noneuropean) unitTest("test 3b", unittest_input.noneuropean == unittest_output.noneuropean)
end end

@ -4,7 +4,7 @@
-- Authentication handler -- Authentication handler
-- --
function minetest.string_to_privs(str, delim) function core.string_to_privs(str, delim)
assert(type(str) == "string") assert(type(str) == "string")
delim = delim or ',' delim = delim or ','
privs = {} privs = {}
@ -14,7 +14,7 @@ function minetest.string_to_privs(str, delim)
return privs return privs
end end
function minetest.privs_to_string(privs, delim) function core.privs_to_string(privs, delim)
assert(type(privs) == "table") assert(type(privs) == "table")
delim = delim or ',' delim = delim or ','
list = {} list = {}
@ -26,17 +26,17 @@ function minetest.privs_to_string(privs, delim)
return table.concat(list, delim) return table.concat(list, delim)
end end
assert(minetest.string_to_privs("a,b").b == true) assert(core.string_to_privs("a,b").b == true)
assert(minetest.privs_to_string({a=true,b=true}) == "a,b") assert(core.privs_to_string({a=true,b=true}) == "a,b")
minetest.auth_file_path = minetest.get_worldpath().."/auth.txt" core.auth_file_path = core.get_worldpath().."/auth.txt"
minetest.auth_table = {} core.auth_table = {}
local function read_auth_file() local function read_auth_file()
local newtable = {} local newtable = {}
local file, errmsg = io.open(minetest.auth_file_path, 'rb') local file, errmsg = io.open(core.auth_file_path, 'rb')
if not file then if not file then
minetest.log("info", minetest.auth_file_path.." could not be opened for reading ("..errmsg.."); assuming new world") core.log("info", core.auth_file_path.." could not be opened for reading ("..errmsg.."); assuming new world")
return return
end end
for line in file:lines() do for line in file:lines() do
@ -45,31 +45,31 @@ local function read_auth_file()
if not name or not password or not privilegestring then if not name or not password or not privilegestring then
error("Invalid line in auth.txt: "..dump(line)) error("Invalid line in auth.txt: "..dump(line))
end end
local privileges = minetest.string_to_privs(privilegestring) local privileges = core.string_to_privs(privilegestring)
newtable[name] = {password=password, privileges=privileges} newtable[name] = {password=password, privileges=privileges}
end end
end end
io.close(file) io.close(file)
minetest.auth_table = newtable core.auth_table = newtable
minetest.notify_authentication_modified() core.notify_authentication_modified()
end end
local function save_auth_file() local function save_auth_file()
local newtable = {} local newtable = {}
-- Check table for validness before attempting to save -- Check table for validness before attempting to save
for name, stuff in pairs(minetest.auth_table) do for name, stuff in pairs(core.auth_table) do
assert(type(name) == "string") assert(type(name) == "string")
assert(name ~= "") assert(name ~= "")
assert(type(stuff) == "table") assert(type(stuff) == "table")
assert(type(stuff.password) == "string") assert(type(stuff.password) == "string")
assert(type(stuff.privileges) == "table") assert(type(stuff.privileges) == "table")
end end
local file, errmsg = io.open(minetest.auth_file_path, 'w+b') local file, errmsg = io.open(core.auth_file_path, 'w+b')
if not file then if not file then
error(minetest.auth_file_path.." could not be opened for writing: "..errmsg) error(core.auth_file_path.." could not be opened for writing: "..errmsg)
end end
for name, stuff in pairs(minetest.auth_table) do for name, stuff in pairs(core.auth_table) do
local privstring = minetest.privs_to_string(stuff.privileges) local privstring = core.privs_to_string(stuff.privileges)
file:write(name..":"..stuff.password..":"..privstring..'\n') file:write(name..":"..stuff.password..":"..privstring..'\n')
end end
io.close(file) io.close(file)
@ -77,7 +77,7 @@ end
read_auth_file() read_auth_file()
minetest.builtin_auth_handler = { core.builtin_auth_handler = {
get_auth = function(name) get_auth = function(name)
assert(type(name) == "string") assert(type(name) == "string")
-- Figure out what password to use for a new player (singleplayer -- Figure out what password to use for a new player (singleplayer
@ -85,52 +85,52 @@ minetest.builtin_auth_handler = {
-- usually empty too) -- usually empty too)
local new_password_hash = "" local new_password_hash = ""
-- If not in authentication table, return nil -- If not in authentication table, return nil
if not minetest.auth_table[name] then if not core.auth_table[name] then
return nil return nil
end end
-- Figure out what privileges the player should have. -- Figure out what privileges the player should have.
-- Take a copy of the privilege table -- Take a copy of the privilege table
local privileges = {} local privileges = {}
for priv, _ in pairs(minetest.auth_table[name].privileges) do for priv, _ in pairs(core.auth_table[name].privileges) do
privileges[priv] = true privileges[priv] = true
end end
-- If singleplayer, give all privileges except those marked as give_to_singleplayer = false -- If singleplayer, give all privileges except those marked as give_to_singleplayer = false
if minetest.is_singleplayer() then if core.is_singleplayer() then
for priv, def in pairs(minetest.registered_privileges) do for priv, def in pairs(core.registered_privileges) do
if def.give_to_singleplayer then if def.give_to_singleplayer then
privileges[priv] = true privileges[priv] = true
end end
end end
-- For the admin, give everything -- For the admin, give everything
elseif name == minetest.setting_get("name") then elseif name == core.setting_get("name") then
for priv, def in pairs(minetest.registered_privileges) do for priv, def in pairs(core.registered_privileges) do
privileges[priv] = true privileges[priv] = true
end end
end end
-- All done -- All done
return { return {
password = minetest.auth_table[name].password, password = core.auth_table[name].password,
privileges = privileges, privileges = privileges,
} }
end, end,
create_auth = function(name, password) create_auth = function(name, password)
assert(type(name) == "string") assert(type(name) == "string")
assert(type(password) == "string") assert(type(password) == "string")
minetest.log('info', "Built-in authentication handler adding player '"..name.."'") core.log('info', "Built-in authentication handler adding player '"..name.."'")
minetest.auth_table[name] = { core.auth_table[name] = {
password = password, password = password,
privileges = minetest.string_to_privs(minetest.setting_get("default_privs")), privileges = core.string_to_privs(core.setting_get("default_privs")),
} }
save_auth_file() save_auth_file()
end, end,
set_password = function(name, password) set_password = function(name, password)
assert(type(name) == "string") assert(type(name) == "string")
assert(type(password) == "string") assert(type(password) == "string")
if not minetest.auth_table[name] then if not core.auth_table[name] then
minetest.builtin_auth_handler.create_auth(name, password) core.builtin_auth_handler.create_auth(name, password)
else else
minetest.log('info', "Built-in authentication handler setting password of player '"..name.."'") core.log('info', "Built-in authentication handler setting password of player '"..name.."'")
minetest.auth_table[name].password = password core.auth_table[name].password = password
save_auth_file() save_auth_file()
end end
return true return true
@ -138,11 +138,11 @@ minetest.builtin_auth_handler = {
set_privileges = function(name, privileges) set_privileges = function(name, privileges)
assert(type(name) == "string") assert(type(name) == "string")
assert(type(privileges) == "table") assert(type(privileges) == "table")
if not minetest.auth_table[name] then if not core.auth_table[name] then
minetest.builtin_auth_handler.create_auth(name, minetest.get_password_hash(name, minetest.setting_get("default_password"))) core.builtin_auth_handler.create_auth(name, core.get_password_hash(name, core.setting_get("default_password")))
end end
minetest.auth_table[name].privileges = privileges core.auth_table[name].privileges = privileges
minetest.notify_authentication_modified(name) core.notify_authentication_modified(name)
save_auth_file() save_auth_file()
end, end,
reload = function() reload = function()
@ -151,36 +151,36 @@ minetest.builtin_auth_handler = {
end, end,
} }
function minetest.register_authentication_handler(handler) function core.register_authentication_handler(handler)
if minetest.registered_auth_handler then if core.registered_auth_handler then
error("Add-on authentication handler already registered by "..minetest.registered_auth_handler_modname) error("Add-on authentication handler already registered by "..core.registered_auth_handler_modname)
end end
minetest.registered_auth_handler = handler core.registered_auth_handler = handler
minetest.registered_auth_handler_modname = minetest.get_current_modname() core.registered_auth_handler_modname = core.get_current_modname()
end end
function minetest.get_auth_handler() function core.get_auth_handler()
if minetest.registered_auth_handler then if core.registered_auth_handler then
return minetest.registered_auth_handler return core.registered_auth_handler
end end
return minetest.builtin_auth_handler return core.builtin_auth_handler
end end
function minetest.set_player_password(name, password) function core.set_player_password(name, password)
if minetest.get_auth_handler().set_password then if core.get_auth_handler().set_password then
minetest.get_auth_handler().set_password(name, password) core.get_auth_handler().set_password(name, password)
end end
end end
function minetest.set_player_privs(name, privs) function core.set_player_privs(name, privs)
if minetest.get_auth_handler().set_privileges then if core.get_auth_handler().set_privileges then
minetest.get_auth_handler().set_privileges(name, privs) core.get_auth_handler().set_privileges(name, privs)
end end
end end
function minetest.auth_reload() function core.auth_reload()
if minetest.get_auth_handler().reload then if core.get_auth_handler().reload then
return minetest.get_auth_handler().reload() return core.get_auth_handler().reload()
end end
return false return false
end end

@ -4,27 +4,27 @@
-- Chat command handler -- Chat command handler
-- --
minetest.chatcommands = {} core.chatcommands = {}
function minetest.register_chatcommand(cmd, def) function core.register_chatcommand(cmd, def)
def = def or {} def = def or {}
def.params = def.params or "" def.params = def.params or ""
def.description = def.description or "" def.description = def.description or ""
def.privs = def.privs or {} def.privs = def.privs or {}
minetest.chatcommands[cmd] = def core.chatcommands[cmd] = def
end end
minetest.register_on_chat_message(function(name, message) core.register_on_chat_message(function(name, message)
local cmd, param = string.match(message, "^/([^ ]+) *(.*)") local cmd, param = string.match(message, "^/([^ ]+) *(.*)")
if not param then if not param then
param = "" param = ""
end end
local cmd_def = minetest.chatcommands[cmd] local cmd_def = core.chatcommands[cmd]
if cmd_def then if cmd_def then
local has_privs, missing_privs = minetest.check_player_privs(name, cmd_def.privs) local has_privs, missing_privs = core.check_player_privs(name, cmd_def.privs)
if has_privs then if has_privs then
cmd_def.func(name, param) cmd_def.func(name, param)
else else
minetest.chat_send_player(name, "You don't have permission to run this command (missing privileges: "..table.concat(missing_privs, ", ")..")") core.chat_send_player(name, "You don't have permission to run this command (missing privileges: "..table.concat(missing_privs, ", ")..")")
end end
return true -- handled chat message return true -- handled chat message
end end
@ -34,16 +34,16 @@ end)
-- --
-- Chat commands -- Chat commands
-- --
minetest.register_chatcommand("me", { core.register_chatcommand("me", {
params = "<action>", params = "<action>",
description = "chat action (eg. /me orders a pizza)", description = "chat action (eg. /me orders a pizza)",
privs = {shout=true}, privs = {shout=true},
func = function(name, param) func = function(name, param)
minetest.chat_send_all("* " .. name .. " " .. param) core.chat_send_all("* " .. name .. " " .. param)
end, end,
}) })
minetest.register_chatcommand("help", { core.register_chatcommand("help", {
privs = {}, privs = {},
params = "(nothing)/all/privs/<cmd>", params = "(nothing)/all/privs/<cmd>",
description = "Get help for commands or list privileges", description = "Get help for commands or list privileges",
@ -57,82 +57,82 @@ minetest.register_chatcommand("help", {
if param == "" then if param == "" then
local msg = "" local msg = ""
cmds = {} cmds = {}
for cmd, def in pairs(minetest.chatcommands) do for cmd, def in pairs(core.chatcommands) do
if minetest.check_player_privs(name, def.privs) then if core.check_player_privs(name, def.privs) then
table.insert(cmds, cmd) table.insert(cmds, cmd)
end end
end end
minetest.chat_send_player(name, "Available commands: "..table.concat(cmds, " ")) core.chat_send_player(name, "Available commands: "..table.concat(cmds, " "))
minetest.chat_send_player(name, "Use '/help <cmd>' to get more information, or '/help all' to list everything.") core.chat_send_player(name, "Use '/help <cmd>' to get more information, or '/help all' to list everything.")
elseif param == "all" then elseif param == "all" then
minetest.chat_send_player(name, "Available commands:") core.chat_send_player(name, "Available commands:")
for cmd, def in pairs(minetest.chatcommands) do for cmd, def in pairs(core.chatcommands) do
if minetest.check_player_privs(name, def.privs) then if core.check_player_privs(name, def.privs) then
minetest.chat_send_player(name, format_help_line(cmd, def)) core.chat_send_player(name, format_help_line(cmd, def))
end end
end end
elseif param == "privs" then elseif param == "privs" then
minetest.chat_send_player(name, "Available privileges:") core.chat_send_player(name, "Available privileges:")
for priv, def in pairs(minetest.registered_privileges) do for priv, def in pairs(core.registered_privileges) do
minetest.chat_send_player(name, priv..": "..def.description) core.chat_send_player(name, priv..": "..def.description)
end end
else else
local cmd = param local cmd = param
def = minetest.chatcommands[cmd] def = core.chatcommands[cmd]
if not def then if not def then
minetest.chat_send_player(name, "Command not available: "..cmd) core.chat_send_player(name, "Command not available: "..cmd)
else else
minetest.chat_send_player(name, format_help_line(cmd, def)) core.chat_send_player(name, format_help_line(cmd, def))
end end
end end
end, end,
}) })
minetest.register_chatcommand("privs", { core.register_chatcommand("privs", {
params = "<name>", params = "<name>",
description = "print out privileges of player", description = "print out privileges of player",
func = function(name, param) func = function(name, param)
if param == "" then if param == "" then
param = name param = name
else else
--[[if not minetest.check_player_privs(name, {privs=true}) then --[[if not core.check_player_privs(name, {privs=true}) then
minetest.chat_send_player(name, "Privileges of "..param.." are hidden from you.") core.chat_send_player(name, "Privileges of "..param.." are hidden from you.")
return return
end]] end]]
end end
minetest.chat_send_player(name, "Privileges of "..param..": "..minetest.privs_to_string(minetest.get_player_privs(param), ' ')) core.chat_send_player(name, "Privileges of "..param..": "..core.privs_to_string(core.get_player_privs(param), ' '))
end, end,
}) })
minetest.register_chatcommand("grant", { core.register_chatcommand("grant", {
params = "<name> <privilege>|all", params = "<name> <privilege>|all",
description = "Give privilege to player", description = "Give privilege to player",
privs = {}, privs = {},
func = function(name, param) func = function(name, param)
if not minetest.check_player_privs(name, {privs=true}) and if not core.check_player_privs(name, {privs=true}) and
not minetest.check_player_privs(name, {basic_privs=true}) then not core.check_player_privs(name, {basic_privs=true}) then
minetest.chat_send_player(name, "Your privileges are insufficient.") core.chat_send_player(name, "Your privileges are insufficient.")
return return
end end
local grantname, grantprivstr = string.match(param, "([^ ]+) (.+)") local grantname, grantprivstr = string.match(param, "([^ ]+) (.+)")
if not grantname or not grantprivstr then if not grantname or not grantprivstr then
minetest.chat_send_player(name, "Invalid parameters (see /help grant)") core.chat_send_player(name, "Invalid parameters (see /help grant)")
return return
elseif not minetest.auth_table[grantname] then elseif not core.auth_table[grantname] then
minetest.chat_send_player(name, "Player "..grantname.." does not exist.") core.chat_send_player(name, "Player "..grantname.." does not exist.")
return return
end end
local grantprivs = minetest.string_to_privs(grantprivstr) local grantprivs = core.string_to_privs(grantprivstr)
if grantprivstr == "all" then if grantprivstr == "all" then
grantprivs = minetest.registered_privileges grantprivs = core.registered_privileges
end end
local privs = minetest.get_player_privs(grantname) local privs = core.get_player_privs(grantname)
local privs_known = true local privs_known = true
for priv, _ in pairs(grantprivs) do for priv, _ in pairs(grantprivs) do
if priv ~= "interact" and priv ~= "shout" and priv ~= "interact_extra" and not minetest.check_player_privs(name, {privs=true}) then if priv ~= "interact" and priv ~= "shout" and priv ~= "interact_extra" and not core.check_player_privs(name, {privs=true}) then
minetest.chat_send_player(name, "Your privileges are insufficient.") core.chat_send_player(name, "Your privileges are insufficient.")
return return
end end
if not minetest.registered_privileges[priv] then if not core.registered_privileges[priv] then
minetest.chat_send_player(name, "Unknown privilege: "..priv) core.chat_send_player(name, "Unknown privilege: "..priv)
privs_known = false privs_known = false
end end
privs[priv] = true privs[priv] = true
@ -140,37 +140,37 @@ minetest.register_chatcommand("grant", {
if not privs_known then if not privs_known then
return return
end end
minetest.set_player_privs(grantname, privs) core.set_player_privs(grantname, privs)
minetest.log(name..' granted ('..minetest.privs_to_string(grantprivs, ', ')..') privileges to '..grantname) core.log(name..' granted ('..core.privs_to_string(grantprivs, ', ')..') privileges to '..grantname)
minetest.chat_send_player(name, "Privileges of "..grantname..": "..minetest.privs_to_string(minetest.get_player_privs(grantname), ' ')) core.chat_send_player(name, "Privileges of "..grantname..": "..core.privs_to_string(core.get_player_privs(grantname), ' '))
if grantname ~= name then if grantname ~= name then
minetest.chat_send_player(grantname, name.." granted you privileges: "..minetest.privs_to_string(grantprivs, ' ')) core.chat_send_player(grantname, name.." granted you privileges: "..core.privs_to_string(grantprivs, ' '))
end end
end, end,
}) })
minetest.register_chatcommand("revoke", { core.register_chatcommand("revoke", {
params = "<name> <privilege>|all", params = "<name> <privilege>|all",
description = "Remove privilege from player", description = "Remove privilege from player",
privs = {}, privs = {},
func = function(name, param) func = function(name, param)
if not minetest.check_player_privs(name, {privs=true}) and if not core.check_player_privs(name, {privs=true}) and
not minetest.check_player_privs(name, {basic_privs=true}) then not core.check_player_privs(name, {basic_privs=true}) then
minetest.chat_send_player(name, "Your privileges are insufficient.") core.chat_send_player(name, "Your privileges are insufficient.")
return return
end end
local revokename, revokeprivstr = string.match(param, "([^ ]+) (.+)") local revokename, revokeprivstr = string.match(param, "([^ ]+) (.+)")
if not revokename or not revokeprivstr then if not revokename or not revokeprivstr then
minetest.chat_send_player(name, "Invalid parameters (see /help revoke)") core.chat_send_player(name, "Invalid parameters (see /help revoke)")
return return
elseif not minetest.auth_table[revokename] then elseif not core.auth_table[revokename] then
minetest.chat_send_player(name, "Player "..revokename.." does not exist.") core.chat_send_player(name, "Player "..revokename.." does not exist.")
return return
end end
local revokeprivs = minetest.string_to_privs(revokeprivstr) local revokeprivs = core.string_to_privs(revokeprivstr)
local privs = minetest.get_player_privs(revokename) local privs = core.get_player_privs(revokename)
for priv, _ in pairs(revokeprivs) do for priv, _ in pairs(revokeprivs) do
if priv ~= "interact" and priv ~= "shout" and priv ~= "interact_extra" and not minetest.check_player_privs(name, {privs=true}) then if priv ~= "interact" and priv ~= "shout" and priv ~= "interact_extra" and not core.check_player_privs(name, {privs=true}) then
minetest.chat_send_player(name, "Your privileges are insufficient.") core.chat_send_player(name, "Your privileges are insufficient.")
return return
end end
end end
@ -181,15 +181,15 @@ minetest.register_chatcommand("revoke", {
privs[priv] = nil privs[priv] = nil
end end
end end
minetest.set_player_privs(revokename, privs) core.set_player_privs(revokename, privs)
minetest.log(name..' revoked ('..minetest.privs_to_string(revokeprivs, ', ')..') privileges from '..revokename) core.log(name..' revoked ('..core.privs_to_string(revokeprivs, ', ')..') privileges from '..revokename)
minetest.chat_send_player(name, "Privileges of "..revokename..": "..minetest.privs_to_string(minetest.get_player_privs(revokename), ' ')) core.chat_send_player(name, "Privileges of "..revokename..": "..core.privs_to_string(core.get_player_privs(revokename), ' '))
if revokename ~= name then if revokename ~= name then
minetest.chat_send_player(revokename, name.." revoked privileges from you: "..minetest.privs_to_string(revokeprivs, ' ')) core.chat_send_player(revokename, name.." revoked privileges from you: "..core.privs_to_string(revokeprivs, ' '))
end end
end, end,
}) })
minetest.register_chatcommand("setpassword", { core.register_chatcommand("setpassword", {
params = "<name> <password>", params = "<name> <password>",
description = "set given password", description = "set given password",
privs = {password=true}, privs = {password=true},
@ -200,53 +200,53 @@ minetest.register_chatcommand("setpassword", {
raw_password = nil raw_password = nil
end end
if not toname then if not toname then
minetest.chat_send_player(name, "Name field required") core.chat_send_player(name, "Name field required")
return return
end end
local actstr = "?" local actstr = "?"
if not raw_password then if not raw_password then
minetest.set_player_password(toname, "") core.set_player_password(toname, "")
actstr = "cleared" actstr = "cleared"
else else
minetest.set_player_password(toname, minetest.get_password_hash(toname, raw_password)) core.set_player_password(toname, core.get_password_hash(toname, raw_password))
actstr = "set" actstr = "set"
end end
minetest.chat_send_player(name, "Password of player \""..toname.."\" "..actstr) core.chat_send_player(name, "Password of player \""..toname.."\" "..actstr)
if toname ~= name then if toname ~= name then
minetest.chat_send_player(toname, "Your password was "..actstr.." by "..name) core.chat_send_player(toname, "Your password was "..actstr.." by "..name)
end end
end, end,
}) })
minetest.register_chatcommand("clearpassword", { core.register_chatcommand("clearpassword", {
params = "<name>", params = "<name>",
description = "set empty password", description = "set empty password",
privs = {password=true}, privs = {password=true},
func = function(name, param) func = function(name, param)
toname = param toname = param
if toname == "" then if toname == "" then
minetest.chat_send_player(name, "Name field required") core.chat_send_player(name, "Name field required")
return return
end end
minetest.set_player_password(toname, '') core.set_player_password(toname, '')
minetest.chat_send_player(name, "Password of player \""..toname.."\" cleared") core.chat_send_player(name, "Password of player \""..toname.."\" cleared")
end, end,
}) })
minetest.register_chatcommand("auth_reload", { core.register_chatcommand("auth_reload", {
params = "", params = "",
description = "reload authentication data", description = "reload authentication data",
privs = {server=true}, privs = {server=true},
func = function(name, param) func = function(name, param)
local done = minetest.auth_reload() local done = core.auth_reload()
if done then if done then
minetest.chat_send_player(name, "Done.") core.chat_send_player(name, "Done.")
else else
minetest.chat_send_player(name, "Failed.") core.chat_send_player(name, "Failed.")
end end
end, end,
}) })
minetest.register_chatcommand("teleport", { core.register_chatcommand("teleport", {
params = "<X>,<Y>,<Z> | <to_name> | <name> <X>,<Y>,<Z> | <name> <to_name>", params = "<X>,<Y>,<Z> | <to_name> | <name> <X>,<Y>,<Z> | <name> <to_name>",
description = "teleport to given position", description = "teleport to given position",
privs = {teleport=true}, privs = {teleport=true},
@ -261,9 +261,9 @@ minetest.register_chatcommand("teleport", {
} }
for _, d in ipairs(tries) do for _, d in ipairs(tries) do
local p = {x = pos.x+d.x, y = pos.y+d.y, z = pos.z+d.z} local p = {x = pos.x+d.x, y = pos.y+d.y, z = pos.z+d.z}
local n = minetest.get_node_or_nil(p) local n = core.get_node_or_nil(p)
if n and n.name then if n and n.name then
local def = minetest.registered_nodes[n.name] local def = core.registered_nodes[n.name]
if def and not def.walkable then if def and not def.walkable then
return p, true return p, true
end end
@ -278,9 +278,9 @@ minetest.register_chatcommand("teleport", {
p.x = tonumber(p.x) p.x = tonumber(p.x)
p.y = tonumber(p.y) p.y = tonumber(p.y)
p.z = tonumber(p.z) p.z = tonumber(p.z)
teleportee = minetest.get_player_by_name(name) teleportee = core.get_player_by_name(name)
if teleportee and p.x and p.y and p.z then if teleportee and p.x and p.y and p.z then
minetest.chat_send_player(name, "Teleporting to ("..p.x..", "..p.y..", "..p.z..")") core.chat_send_player(name, "Teleporting to ("..p.x..", "..p.y..", "..p.z..")")
teleportee:setpos(p) teleportee:setpos(p)
return return
end end
@ -289,21 +289,21 @@ minetest.register_chatcommand("teleport", {
local p = nil local p = nil
local target_name = nil local target_name = nil
target_name = string.match(param, "^([^ ]+)$") target_name = string.match(param, "^([^ ]+)$")
teleportee = minetest.get_player_by_name(name) teleportee = core.get_player_by_name(name)
if target_name then if target_name then
local target = minetest.get_player_by_name(target_name) local target = core.get_player_by_name(target_name)
if target then if target then
p = target:getpos() p = target:getpos()
end end
end end
if teleportee and p then if teleportee and p then
p = find_free_position_near(p) p = find_free_position_near(p)
minetest.chat_send_player(name, "Teleporting to "..target_name.." at ("..p.x..", "..p.y..", "..p.z..")") core.chat_send_player(name, "Teleporting to "..target_name.." at ("..p.x..", "..p.y..", "..p.z..")")
teleportee:setpos(p) teleportee:setpos(p)
return return
end end
if minetest.check_player_privs(name, {bring=true}) then if core.check_player_privs(name, {bring=true}) then
local teleportee = nil local teleportee = nil
local p = {} local p = {}
local teleportee_name = nil local teleportee_name = nil
@ -312,10 +312,10 @@ minetest.register_chatcommand("teleport", {
p.y = tonumber(p.y) p.y = tonumber(p.y)
p.z = tonumber(p.z) p.z = tonumber(p.z)
if teleportee_name then if teleportee_name then
teleportee = minetest.get_player_by_name(teleportee_name) teleportee = core.get_player_by_name(teleportee_name)
end end
if teleportee and p.x and p.y and p.z then if teleportee and p.x and p.y and p.z then
minetest.chat_send_player(name, "Teleporting "..teleportee_name.." to ("..p.x..", "..p.y..", "..p.z..")") core.chat_send_player(name, "Teleporting "..teleportee_name.." to ("..p.x..", "..p.y..", "..p.z..")")
teleportee:setpos(p) teleportee:setpos(p)
return return
end end
@ -326,68 +326,68 @@ minetest.register_chatcommand("teleport", {
local target_name = nil local target_name = nil
teleportee_name, target_name = string.match(param, "^([^ ]+) +([^ ]+)$") teleportee_name, target_name = string.match(param, "^([^ ]+) +([^ ]+)$")
if teleportee_name then if teleportee_name then
teleportee = minetest.get_player_by_name(teleportee_name) teleportee = core.get_player_by_name(teleportee_name)
end end
if target_name then if target_name then
local target = minetest.get_player_by_name(target_name) local target = core.get_player_by_name(target_name)
if target then if target then
p = target:getpos() p = target:getpos()
end end
end end
if teleportee and p then if teleportee and p then
p = find_free_position_near(p) p = find_free_position_near(p)
minetest.chat_send_player(name, "Teleporting "..teleportee_name.." to "..target_name.." at ("..p.x..", "..p.y..", "..p.z..")") core.chat_send_player(name, "Teleporting "..teleportee_name.." to "..target_name.." at ("..p.x..", "..p.y..", "..p.z..")")
teleportee:setpos(p) teleportee:setpos(p)
return return
end end
end end
minetest.chat_send_player(name, "Invalid parameters (\""..param.."\") or player not found (see /help teleport)") core.chat_send_player(name, "Invalid parameters (\""..param.."\") or player not found (see /help teleport)")
return return
end, end,
}) })
minetest.register_chatcommand("set", { core.register_chatcommand("set", {
params = "[-n] <name> <value> | <name>", params = "[-n] <name> <value> | <name>",
description = "set or read server configuration setting", description = "set or read server configuration setting",
privs = {server=true}, privs = {server=true},
func = function(name, param) func = function(name, param)
local arg, setname, setvalue = string.match(param, "(-[n]) ([^ ]+) (.+)") local arg, setname, setvalue = string.match(param, "(-[n]) ([^ ]+) (.+)")
if arg and arg == "-n" and setname and setvalue then if arg and arg == "-n" and setname and setvalue then
minetest.setting_set(setname, setvalue) core.setting_set(setname, setvalue)
minetest.chat_send_player(name, setname.." = "..setvalue) core.chat_send_player(name, setname.." = "..setvalue)
return return
end end
local setname, setvalue = string.match(param, "([^ ]+) (.+)") local setname, setvalue = string.match(param, "([^ ]+) (.+)")
if setname and setvalue then if setname and setvalue then
if not minetest.setting_get(setname) then if not core.setting_get(setname) then
minetest.chat_send_player(name, "Failed. Use '/set -n <name> <value>' to create a new setting.") core.chat_send_player(name, "Failed. Use '/set -n <name> <value>' to create a new setting.")
return return
end end
minetest.setting_set(setname, setvalue) core.setting_set(setname, setvalue)
minetest.chat_send_player(name, setname.." = "..setvalue) core.chat_send_player(name, setname.." = "..setvalue)
return return
end end
local setname = string.match(param, "([^ ]+)") local setname = string.match(param, "([^ ]+)")
if setname then if setname then
local setvalue = minetest.setting_get(setname) local setvalue = core.setting_get(setname)
if not setvalue then if not setvalue then
setvalue = "<not set>" setvalue = "<not set>"
end end
minetest.chat_send_player(name, setname.." = "..setvalue) core.chat_send_player(name, setname.." = "..setvalue)
return return
end end
minetest.chat_send_player(name, "Invalid parameters (see /help set)") core.chat_send_player(name, "Invalid parameters (see /help set)")
end, end,
}) })
minetest.register_chatcommand("mods", { core.register_chatcommand("mods", {
params = "", params = "",
description = "lists mods installed on the server", description = "lists mods installed on the server",
privs = {}, privs = {},
func = function(name, param) func = function(name, param)
local response = "" local response = ""
local modnames = minetest.get_modnames() local modnames = core.get_modnames()
for i, mod in ipairs(modnames) do for i, mod in ipairs(modnames) do
response = response .. mod response = response .. mod
-- Add space if not at the end -- Add space if not at the end
@ -395,25 +395,25 @@ minetest.register_chatcommand("mods", {
response = response .. " " response = response .. " "
end end
end end
minetest.chat_send_player(name, response) core.chat_send_player(name, response)
end, end,
}) })
local function handle_give_command(cmd, giver, receiver, stackstring) local function handle_give_command(cmd, giver, receiver, stackstring)
minetest.log("action", giver.." invoked "..cmd..', stackstring="' core.log("action", giver.." invoked "..cmd..', stackstring="'
..stackstring..'"') ..stackstring..'"')
minetest.log(cmd..' invoked, stackstring="'..stackstring..'"') core.log(cmd..' invoked, stackstring="'..stackstring..'"')
local itemstack = ItemStack(stackstring) local itemstack = ItemStack(stackstring)
if itemstack:is_empty() then if itemstack:is_empty() then
minetest.chat_send_player(giver, 'error: cannot give an empty item') core.chat_send_player(giver, 'error: cannot give an empty item')
return return
elseif not itemstack:is_known() then elseif not itemstack:is_known() then
minetest.chat_send_player(giver, 'error: cannot give an unknown item') core.chat_send_player(giver, 'error: cannot give an unknown item')
return return
end end
local receiverref = minetest.get_player_by_name(receiver) local receiverref = core.get_player_by_name(receiver)
if receiverref == nil then if receiverref == nil then
minetest.chat_send_player(giver, receiver..' is not a known player') core.chat_send_player(giver, receiver..' is not a known player')
return return
end end
local leftover = receiverref:get_inventory():add_item("main", itemstack) local leftover = receiverref:get_inventory():add_item("main", itemstack)
@ -428,96 +428,96 @@ local function handle_give_command(cmd, giver, receiver, stackstring)
-- entered (e.g. big numbers are always interpreted as 2^16-1). -- entered (e.g. big numbers are always interpreted as 2^16-1).
stackstring = itemstack:to_string() stackstring = itemstack:to_string()
if giver == receiver then if giver == receiver then
minetest.chat_send_player(giver, '"'..stackstring core.chat_send_player(giver, '"'..stackstring
..'" '..partiality..'added to inventory.'); ..'" '..partiality..'added to inventory.');
else else
minetest.chat_send_player(giver, '"'..stackstring core.chat_send_player(giver, '"'..stackstring
..'" '..partiality..'added to '..receiver..'\'s inventory.'); ..'" '..partiality..'added to '..receiver..'\'s inventory.');
minetest.chat_send_player(receiver, '"'..stackstring core.chat_send_player(receiver, '"'..stackstring
..'" '..partiality..'added to inventory.'); ..'" '..partiality..'added to inventory.');
end end
end end
minetest.register_chatcommand("give", { core.register_chatcommand("give", {
params = "<name> <itemstring>", params = "<name> <itemstring>",
description = "give item to player", description = "give item to player",
privs = {give=true}, privs = {give=true},
func = function(name, param) func = function(name, param)
local toname, itemstring = string.match(param, "^([^ ]+) +(.+)$") local toname, itemstring = string.match(param, "^([^ ]+) +(.+)$")
if not toname or not itemstring then if not toname or not itemstring then
minetest.chat_send_player(name, "name and itemstring required") core.chat_send_player(name, "name and itemstring required")
return return
end end
handle_give_command("/give", name, toname, itemstring) handle_give_command("/give", name, toname, itemstring)
end, end,
}) })
minetest.register_chatcommand("giveme", { core.register_chatcommand("giveme", {
params = "<itemstring>", params = "<itemstring>",
description = "give item to yourself", description = "give item to yourself",
privs = {give=true}, privs = {give=true},
func = function(name, param) func = function(name, param)
local itemstring = string.match(param, "(.+)$") local itemstring = string.match(param, "(.+)$")
if not itemstring then if not itemstring then
minetest.chat_send_player(name, "itemstring required") core.chat_send_player(name, "itemstring required")
return return
end end
handle_give_command("/giveme", name, name, itemstring) handle_give_command("/giveme", name, name, itemstring)
end, end,
}) })
minetest.register_chatcommand("spawnentity", { core.register_chatcommand("spawnentity", {
params = "<entityname>", params = "<entityname>",
description = "spawn entity at your position", description = "spawn entity at your position",
privs = {give=true, interact=true}, privs = {give=true, interact=true},
func = function(name, param) func = function(name, param)
local entityname = string.match(param, "(.+)$") local entityname = string.match(param, "(.+)$")
if not entityname then if not entityname then
minetest.chat_send_player(name, "entityname required") core.chat_send_player(name, "entityname required")
return return
end end
minetest.log("action", '/spawnentity invoked, entityname="'..entityname..'"') core.log("action", '/spawnentity invoked, entityname="'..entityname..'"')
local player = minetest.get_player_by_name(name) local player = core.get_player_by_name(name)
if player == nil then if player == nil then
minetest.log("error", "Unable to spawn entity, player is nil") core.log("error", "Unable to spawn entity, player is nil")
return true -- Handled chat message return true -- Handled chat message
end end
local p = player:getpos() local p = player:getpos()
p.y = p.y + 1 p.y = p.y + 1
minetest.add_entity(p, entityname) core.add_entity(p, entityname)
minetest.chat_send_player(name, '"'..entityname core.chat_send_player(name, '"'..entityname
..'" spawned.'); ..'" spawned.');
end, end,
}) })
minetest.register_chatcommand("pulverize", { core.register_chatcommand("pulverize", {
params = "", params = "",
description = "delete item in hand", description = "delete item in hand",
privs = {}, privs = {},
func = function(name, param) func = function(name, param)
local player = minetest.get_player_by_name(name) local player = core.get_player_by_name(name)
if player == nil then if player == nil then
minetest.log("error", "Unable to pulverize, player is nil") core.log("error", "Unable to pulverize, player is nil")
return true -- Handled chat message return true -- Handled chat message
end end
if player:get_wielded_item():is_empty() then if player:get_wielded_item():is_empty() then
minetest.chat_send_player(name, 'Unable to pulverize, no item in hand.') core.chat_send_player(name, 'Unable to pulverize, no item in hand.')
else else
player:set_wielded_item(nil) player:set_wielded_item(nil)
minetest.chat_send_player(name, 'An item was pulverized.') core.chat_send_player(name, 'An item was pulverized.')
end end
end, end,
}) })
-- Key = player name -- Key = player name
minetest.rollback_punch_callbacks = {} core.rollback_punch_callbacks = {}
minetest.register_on_punchnode(function(pos, node, puncher) core.register_on_punchnode(function(pos, node, puncher)
local name = puncher:get_player_name() local name = puncher:get_player_name()
if minetest.rollback_punch_callbacks[name] then if core.rollback_punch_callbacks[name] then
minetest.rollback_punch_callbacks[name](pos, node, puncher) core.rollback_punch_callbacks[name](pos, node, puncher)
minetest.rollback_punch_callbacks[name] = nil core.rollback_punch_callbacks[name] = nil
end end
end) end)
minetest.register_chatcommand("rollback_check", { core.register_chatcommand("rollback_check", {
params = "[<range>] [<seconds>] [limit]", params = "[<range>] [<seconds>] [limit]",
description = "check who has last touched a node or near it, ".. description = "check who has last touched a node or near it, "..
"max. <seconds> ago (default range=0, seconds=86400=24h, limit=5)", "max. <seconds> ago (default range=0, seconds=86400=24h, limit=5)",
@ -529,29 +529,29 @@ minetest.register_chatcommand("rollback_check", {
seconds = tonumber(seconds) or 86400 seconds = tonumber(seconds) or 86400
limit = tonumber(limit) or 5 limit = tonumber(limit) or 5
if limit > 100 then if limit > 100 then
minetest.chat_send_player(name, "That limit is too high!") core.chat_send_player(name, "That limit is too high!")
return return
end end
minetest.chat_send_player(name, "Punch a node (range=".. core.chat_send_player(name, "Punch a node (range="..
range..", seconds="..seconds.."s, limit="..limit..")") range..", seconds="..seconds.."s, limit="..limit..")")
minetest.rollback_punch_callbacks[name] = function(pos, node, puncher) core.rollback_punch_callbacks[name] = function(pos, node, puncher)
local name = puncher:get_player_name() local name = puncher:get_player_name()
minetest.chat_send_player(name, "Checking "..minetest.pos_to_string(pos).."...") core.chat_send_player(name, "Checking "..core.pos_to_string(pos).."...")
local actions = minetest.rollback_get_node_actions(pos, range, seconds, limit) local actions = core.rollback_get_node_actions(pos, range, seconds, limit)
local num_actions = #actions local num_actions = #actions
if num_actions == 0 then if num_actions == 0 then
minetest.chat_send_player(name, "Nobody has touched the ".. core.chat_send_player(name, "Nobody has touched the "..
"specified location in "..seconds.." seconds") "specified location in "..seconds.." seconds")
return return
end end
local time = os.time() local time = os.time()
for i = num_actions, 1, -1 do for i = num_actions, 1, -1 do
local action = actions[i] local action = actions[i]
minetest.chat_send_player(name, core.chat_send_player(name,
("%s %s %s -> %s %d seconds ago.") ("%s %s %s -> %s %d seconds ago.")
:format( :format(
minetest.pos_to_string(action.pos), core.pos_to_string(action.pos),
action.actor, action.actor,
action.oldnode.name, action.oldnode.name,
action.newnode.name, action.newnode.name,
@ -561,7 +561,7 @@ minetest.register_chatcommand("rollback_check", {
end, end,
}) })
minetest.register_chatcommand("rollback", { core.register_chatcommand("rollback", {
params = "<player name> [<seconds>] | :<actor> [<seconds>]", params = "<player name> [<seconds>] | :<actor> [<seconds>]",
description = "revert actions of a player; default for <seconds> is 60", description = "revert actions of a player; default for <seconds> is 60",
privs = {rollback=true}, privs = {rollback=true},
@ -571,109 +571,109 @@ minetest.register_chatcommand("rollback", {
local player_name = nil local player_name = nil
player_name, seconds = string.match(param, "([^ ]+) *(%d*)") player_name, seconds = string.match(param, "([^ ]+) *(%d*)")
if not player_name then if not player_name then
minetest.chat_send_player(name, "Invalid parameters. See /help rollback and /help rollback_check") core.chat_send_player(name, "Invalid parameters. See /help rollback and /help rollback_check")
return return
end end
target_name = "player:"..player_name target_name = "player:"..player_name
end end
seconds = tonumber(seconds) or 60 seconds = tonumber(seconds) or 60
minetest.chat_send_player(name, "Reverting actions of ".. core.chat_send_player(name, "Reverting actions of "..
target_name.." since "..seconds.." seconds.") target_name.." since "..seconds.." seconds.")
local success, log = minetest.rollback_revert_actions_by( local success, log = core.rollback_revert_actions_by(
target_name, seconds) target_name, seconds)
if #log > 100 then if #log > 100 then
minetest.chat_send_player(name, "(log is too long to show)") core.chat_send_player(name, "(log is too long to show)")
else else
for _, line in pairs(log) do for _, line in pairs(log) do
minetest.chat_send_player(name, line) core.chat_send_player(name, line)
end end
end end
if success then if success then
minetest.chat_send_player(name, "Reverting actions succeeded.") core.chat_send_player(name, "Reverting actions succeeded.")
else else
minetest.chat_send_player(name, "Reverting actions FAILED.") core.chat_send_player(name, "Reverting actions FAILED.")
end end
end, end,
}) })
minetest.register_chatcommand("status", { core.register_chatcommand("status", {
params = "", params = "",
description = "print server status line", description = "print server status line",
privs = {}, privs = {},
func = function(name, param) func = function(name, param)
minetest.chat_send_player(name, minetest.get_server_status()) core.chat_send_player(name, core.get_server_status())
end, end,
}) })
minetest.register_chatcommand("time", { core.register_chatcommand("time", {
params = "<0...24000>", params = "<0...24000>",
description = "set time of day", description = "set time of day",
privs = {settime=true}, privs = {settime=true},
func = function(name, param) func = function(name, param)
if param == "" then if param == "" then
minetest.chat_send_player(name, "Missing parameter") core.chat_send_player(name, "Missing parameter")
return return
end end
local newtime = tonumber(param) local newtime = tonumber(param)
if newtime == nil then if newtime == nil then
minetest.chat_send_player(name, "Invalid time") core.chat_send_player(name, "Invalid time")
else else
minetest.set_timeofday((newtime % 24000) / 24000) core.set_timeofday((newtime % 24000) / 24000)
minetest.chat_send_player(name, "Time of day changed.") core.chat_send_player(name, "Time of day changed.")
minetest.log("action", name .. " sets time " .. newtime) core.log("action", name .. " sets time " .. newtime)
end end
end, end,
}) })
minetest.register_chatcommand("shutdown", { core.register_chatcommand("shutdown", {
params = "", params = "",
description = "shutdown server", description = "shutdown server",
privs = {server=true}, privs = {server=true},
func = function(name, param) func = function(name, param)
minetest.log("action", name .. " shuts down server") core.log("action", name .. " shuts down server")
minetest.request_shutdown() core.request_shutdown()
minetest.chat_send_all("*** Server shutting down (operator request).") core.chat_send_all("*** Server shutting down (operator request).")
end, end,
}) })
minetest.register_chatcommand("ban", { core.register_chatcommand("ban", {
params = "<name>", params = "<name>",
description = "ban IP of player", description = "ban IP of player",
privs = {ban=true}, privs = {ban=true},
func = function(name, param) func = function(name, param)
if param == "" then if param == "" then
minetest.chat_send_player(name, "Ban list: " .. minetest.get_ban_list()) core.chat_send_player(name, "Ban list: " .. core.get_ban_list())
return return
end end
if not minetest.get_player_by_name(param) then if not core.get_player_by_name(param) then
minetest.chat_send_player(name, "No such player") core.chat_send_player(name, "No such player")
return return
end end
if not minetest.ban_player(param) then if not core.ban_player(param) then
minetest.chat_send_player(name, "Failed to ban player") core.chat_send_player(name, "Failed to ban player")
else else
local desc = minetest.get_ban_description(param) local desc = core.get_ban_description(param)
minetest.chat_send_player(name, "Banned " .. desc .. ".") core.chat_send_player(name, "Banned " .. desc .. ".")
minetest.log("action", name .. " bans " .. desc .. ".") core.log("action", name .. " bans " .. desc .. ".")
end end
end, end,
}) })
minetest.register_chatcommand("unban", { core.register_chatcommand("unban", {
params = "<name/ip>", params = "<name/ip>",
description = "remove IP ban", description = "remove IP ban",
privs = {ban=true}, privs = {ban=true},
func = function(name, param) func = function(name, param)
if not minetest.unban_player_or_ip(param) then if not core.unban_player_or_ip(param) then
minetest.chat_send_player(name, "Failed to unban player/IP") core.chat_send_player(name, "Failed to unban player/IP")
else else
minetest.chat_send_player(name, "Unbanned " .. param) core.chat_send_player(name, "Unbanned " .. param)
minetest.log("action", name .. " unbans " .. param) core.log("action", name .. " unbans " .. param)
end end
end, end,
}) })
minetest.register_chatcommand("kick", { core.register_chatcommand("kick", {
params = "<name> [reason]", params = "<name> [reason]",
description = "kick a player", description = "kick a player",
privs = {kick=true}, privs = {kick=true},
@ -682,44 +682,44 @@ minetest.register_chatcommand("kick", {
if not tokick then if not tokick then
tokick = param tokick = param
end end
if not minetest.kick_player(tokick, reason) then if not core.kick_player(tokick, reason) then
minetest.chat_send_player(name, "Failed to kick player " .. tokick) core.chat_send_player(name, "Failed to kick player " .. tokick)
else else
minetest.chat_send_player(name, "kicked " .. tokick) core.chat_send_player(name, "kicked " .. tokick)
minetest.log("action", name .. " kicked " .. tokick) core.log("action", name .. " kicked " .. tokick)
end end
end, end,
}) })
minetest.register_chatcommand("clearobjects", { core.register_chatcommand("clearobjects", {
params = "", params = "",
description = "clear all objects in world", description = "clear all objects in world",
privs = {server=true}, privs = {server=true},
func = function(name, param) func = function(name, param)
minetest.log("action", name .. " clears all objects") core.log("action", name .. " clears all objects")
minetest.chat_send_all("Clearing all objects. This may take long. You may experience a timeout. (by " .. name .. ")") core.chat_send_all("Clearing all objects. This may take long. You may experience a timeout. (by " .. name .. ")")
minetest.clear_objects() core.clear_objects()
minetest.log("action", "object clearing done") core.log("action", "object clearing done")
minetest.chat_send_all("*** Cleared all objects.") core.chat_send_all("*** Cleared all objects.")
end, end,
}) })
minetest.register_chatcommand("msg", { core.register_chatcommand("msg", {
params = "<name> <message>", params = "<name> <message>",
description = "Send a private message", description = "Send a private message",
privs = {shout=true}, privs = {shout=true},
func = function(name, param) func = function(name, param)
local found, _, sendto, message = param:find("^([^%s]+)%s(.+)$") local found, _, sendto, message = param:find("^([^%s]+)%s(.+)$")
if found then if found then
if minetest.get_player_by_name(sendto) then if core.get_player_by_name(sendto) then
minetest.log("action", "PM from "..name.." to "..sendto..": "..message) core.log("action", "PM from "..name.." to "..sendto..": "..message)
minetest.chat_send_player(sendto, "PM from "..name..": "..message) core.chat_send_player(sendto, "PM from "..name..": "..message)
minetest.chat_send_player(name, "Message sent") core.chat_send_player(name, "Message sent")
else else
minetest.chat_send_player(name, "The player "..sendto.." is not online") core.chat_send_player(name, "The player "..sendto.." is not online")
end end
else else
minetest.chat_send_player(name, "Invalid usage, see /help msg") core.chat_send_player(name, "Invalid usage, see /help msg")
end end
end, end,
}) })

@ -4,38 +4,38 @@
-- Default material types -- Default material types
-- --
function digprop_err() function digprop_err()
minetest.log("info", debug.traceback()) core.log("info", debug.traceback())
minetest.log("info", "WARNING: The minetest.digprop_* functions are obsolete and need to be replaced by item groups.") core.log("info", "WARNING: The core.digprop_* functions are obsolete and need to be replaced by item groups.")
end end
minetest.digprop_constanttime = digprop_err core.digprop_constanttime = digprop_err
minetest.digprop_stonelike = digprop_err core.digprop_stonelike = digprop_err
minetest.digprop_dirtlike = digprop_err core.digprop_dirtlike = digprop_err
minetest.digprop_gravellike = digprop_err core.digprop_gravellike = digprop_err
minetest.digprop_woodlike = digprop_err core.digprop_woodlike = digprop_err
minetest.digprop_leaveslike = digprop_err core.digprop_leaveslike = digprop_err
minetest.digprop_glasslike = digprop_err core.digprop_glasslike = digprop_err
minetest.node_metadata_inventory_move_allow_all = function() core.node_metadata_inventory_move_allow_all = function()
minetest.log("info", "WARNING: minetest.node_metadata_inventory_move_allow_all is obsolete and does nothing.") core.log("info", "WARNING: core.node_metadata_inventory_move_allow_all is obsolete and does nothing.")
end end
minetest.add_to_creative_inventory = function(itemstring) core.add_to_creative_inventory = function(itemstring)
minetest.log('info', "WARNING: minetest.add_to_creative_inventory: This function is deprecated and does nothing.") core.log('info', "WARNING: core.add_to_creative_inventory: This function is deprecated and does nothing.")
end end
-- --
-- EnvRef -- EnvRef
-- --
minetest.env = {} core.env = {}
local envref_deprecation_message_printed = false local envref_deprecation_message_printed = false
setmetatable(minetest.env, { setmetatable(core.env, {
__index = function(table, key) __index = function(table, key)
if not envref_deprecation_message_printed then if not envref_deprecation_message_printed then
minetest.log("info", "WARNING: minetest.env:[...] is deprecated and should be replaced with minetest.[...]") core.log("info", "WARNING: core.env:[...] is deprecated and should be replaced with core.[...]")
envref_deprecation_message_printed = true envref_deprecation_message_printed = true
end end
local func = minetest[key] local func = core[key]
if type(func) == "function" then if type(func) == "function" then
rawset(table, key, function(self, ...) rawset(table, key, function(self, ...)
return func(...) return func(...)
@ -47,7 +47,7 @@ setmetatable(minetest.env, {
end end
}) })
function minetest.rollback_get_last_node_actor(pos, range, seconds) function core.rollback_get_last_node_actor(pos, range, seconds)
return minetest.rollback_get_node_actions(pos, range, seconds, 1)[1] return core.rollback_get_node_actions(pos, range, seconds, 1)[1]
end end

@ -1,8 +1,8 @@
-- Minetest: builtin/detached_inventory.lua -- Minetest: builtin/detached_inventory.lua
minetest.detached_inventories = {} core.detached_inventories = {}
function minetest.create_detached_inventory(name, callbacks) function core.create_detached_inventory(name, callbacks)
local stuff = {} local stuff = {}
stuff.name = name stuff.name = name
if callbacks then if callbacks then
@ -13,7 +13,7 @@ function minetest.create_detached_inventory(name, callbacks)
stuff.on_put = callbacks.on_put stuff.on_put = callbacks.on_put
stuff.on_take = callbacks.on_take stuff.on_take = callbacks.on_take
end end
minetest.detached_inventories[name] = stuff core.detached_inventories[name] = stuff
return minetest.create_detached_inventory_raw(name) return core.create_detached_inventory_raw(name)
end end

@ -4,7 +4,7 @@
-- Falling stuff -- Falling stuff
-- --
minetest.register_entity(":__builtin:falling_node", { core.register_entity(":__builtin:falling_node", {
initial_properties = { initial_properties = {
physical = true, physical = true,
collide_with_objects = false, collide_with_objects = false,
@ -26,9 +26,9 @@ minetest.register_entity(":__builtin:falling_node", {
end end
local item_texture = nil local item_texture = nil
local item_type = "" local item_type = ""
if minetest.registered_items[itemname] then if core.registered_items[itemname] then
item_texture = minetest.registered_items[itemname].inventory_image item_texture = core.registered_items[itemname].inventory_image
item_type = minetest.registered_items[itemname].type item_type = core.registered_items[itemname].type
end end
prop = { prop = {
is_visible = true, is_visible = true,
@ -53,12 +53,12 @@ minetest.register_entity(":__builtin:falling_node", {
-- Turn to actual sand when collides to ground or just move -- Turn to actual sand when collides to ground or just move
local pos = self.object:getpos() local pos = self.object:getpos()
local bcp = {x=pos.x, y=pos.y-0.7, z=pos.z} -- Position of bottom center point local bcp = {x=pos.x, y=pos.y-0.7, z=pos.z} -- Position of bottom center point
local bcn = minetest.get_node(bcp) local bcn = core.get_node(bcp)
local bcd = minetest.registered_nodes[bcn.name] local bcd = core.registered_nodes[bcn.name]
-- Note: walkable is in the node definition, not in item groups -- Note: walkable is in the node definition, not in item groups
if not bcd or if not bcd or
(bcd.walkable or (bcd.walkable or
(minetest.get_item_group(self.node.name, "float") ~= 0 and (core.get_item_group(self.node.name, "float") ~= 0 and
bcd.liquidtype ~= "none")) then bcd.liquidtype ~= "none")) then
if bcd and bcd.leveled and if bcd and bcd.leveled and
bcn.name == self.node.name then bcn.name == self.node.name then
@ -66,38 +66,38 @@ minetest.register_entity(":__builtin:falling_node", {
if addlevel == nil or addlevel <= 0 then if addlevel == nil or addlevel <= 0 then
addlevel = bcd.leveled addlevel = bcd.leveled
end end
if minetest.add_node_level(bcp, addlevel) == 0 then if core.add_node_level(bcp, addlevel) == 0 then
self.object:remove() self.object:remove()
return return
end end
elseif bcd and bcd.buildable_to and elseif bcd and bcd.buildable_to and
(minetest.get_item_group(self.node.name, "float") == 0 or (core.get_item_group(self.node.name, "float") == 0 or
bcd.liquidtype == "none") then bcd.liquidtype == "none") then
minetest.remove_node(bcp) core.remove_node(bcp)
return return
end end
local np = {x=bcp.x, y=bcp.y+1, z=bcp.z} local np = {x=bcp.x, y=bcp.y+1, z=bcp.z}
-- Check what's here -- Check what's here
local n2 = minetest.get_node(np) local n2 = core.get_node(np)
-- If it's not air or liquid, remove node and replace it with -- If it's not air or liquid, remove node and replace it with
-- it's drops -- it's drops
if n2.name ~= "air" and (not minetest.registered_nodes[n2.name] or if n2.name ~= "air" and (not core.registered_nodes[n2.name] or
minetest.registered_nodes[n2.name].liquidtype == "none") then core.registered_nodes[n2.name].liquidtype == "none") then
local drops = minetest.get_node_drops(n2.name, "") local drops = core.get_node_drops(n2.name, "")
minetest.remove_node(np) core.remove_node(np)
-- Add dropped items -- Add dropped items
local _, dropped_item local _, dropped_item
for _, dropped_item in ipairs(drops) do for _, dropped_item in ipairs(drops) do
minetest.add_item(np, dropped_item) core.add_item(np, dropped_item)
end end
-- Run script hook -- Run script hook
local _, callback local _, callback
for _, callback in ipairs(minetest.registered_on_dignodes) do for _, callback in ipairs(core.registered_on_dignodes) do
callback(np, n2, nil) callback(np, n2, nil)
end end
end end
-- Create node and remove entity -- Create node and remove entity
minetest.add_node(np, self.node) core.add_node(np, self.node)
self.object:remove() self.object:remove()
nodeupdate(np) nodeupdate(np)
else else
@ -107,25 +107,25 @@ minetest.register_entity(":__builtin:falling_node", {
}) })
function spawn_falling_node(p, node) function spawn_falling_node(p, node)
obj = minetest.add_entity(p, "__builtin:falling_node") obj = core.add_entity(p, "__builtin:falling_node")
obj:get_luaentity():set_node(node) obj:get_luaentity():set_node(node)
end end
function drop_attached_node(p) function drop_attached_node(p)
local nn = minetest.get_node(p).name local nn = core.get_node(p).name
minetest.remove_node(p) core.remove_node(p)
for _,item in ipairs(minetest.get_node_drops(nn, "")) do for _,item in ipairs(core.get_node_drops(nn, "")) do
local pos = { local pos = {
x = p.x + math.random()/2 - 0.25, x = p.x + math.random()/2 - 0.25,
y = p.y + math.random()/2 - 0.25, y = p.y + math.random()/2 - 0.25,
z = p.z + math.random()/2 - 0.25, z = p.z + math.random()/2 - 0.25,
} }
minetest.add_item(pos, item) core.add_item(pos, item)
end end
end end
function check_attached_node(p, n) function check_attached_node(p, n)
local def = minetest.registered_nodes[n.name] local def = core.registered_nodes[n.name]
local d = {x=0, y=0, z=0} local d = {x=0, y=0, z=0}
if def.paramtype2 == "wallmounted" then if def.paramtype2 == "wallmounted" then
if n.param2 == 0 then if n.param2 == 0 then
@ -145,8 +145,8 @@ function check_attached_node(p, n)
d.y = -1 d.y = -1
end end
local p2 = {x=p.x+d.x, y=p.y+d.y, z=p.z+d.z} local p2 = {x=p.x+d.x, y=p.y+d.y, z=p.z+d.z}
local nn = minetest.get_node(p2).name local nn = core.get_node(p2).name
local def2 = minetest.registered_nodes[nn] local def2 = core.registered_nodes[nn]
if def2 and not def2.walkable then if def2 and not def2.walkable then
return false return false
end end
@ -158,28 +158,30 @@ end
-- --
function nodeupdate_single(p, delay) function nodeupdate_single(p, delay)
n = minetest.get_node(p) n = core.get_node(p)
if minetest.get_item_group(n.name, "falling_node") ~= 0 then if core.get_item_group(n.name, "falling_node") ~= 0 then
p_bottom = {x=p.x, y=p.y-1, z=p.z} p_bottom = {x=p.x, y=p.y-1, z=p.z}
n_bottom = minetest.get_node(p_bottom) n_bottom = core.get_node(p_bottom)
-- Note: walkable is in the node definition, not in item groups -- Note: walkable is in the node definition, not in item groups
if minetest.registered_nodes[n_bottom.name] and if core.registered_nodes[n_bottom.name] and
(minetest.get_item_group(n.name, "float") == 0 or minetest.registered_nodes[n_bottom.name].liquidtype == "none") and (core.get_item_group(n.name, "float") == 0 or
(n.name ~= n_bottom.name or (minetest.registered_nodes[n_bottom.name].leveled and minetest.env:get_node_level(p_bottom) < minetest.env:get_node_max_level(p_bottom))) and core.registered_nodes[n_bottom.name].liquidtype == "none") and
(not minetest.registered_nodes[n_bottom.name].walkable or (n.name ~= n_bottom.name or (core.registered_nodes[n_bottom.name].leveled and
minetest.registered_nodes[n_bottom.name].buildable_to) then core.get_node_level(p_bottom) < core.get_node_max_level(p_bottom))) and
(not core.registered_nodes[n_bottom.name].walkable or
core.registered_nodes[n_bottom.name].buildable_to) then
if delay then if delay then
minetest.after(0.1, nodeupdate_single, {x=p.x, y=p.y, z=p.z}, false) core.after(0.1, nodeupdate_single, {x=p.x, y=p.y, z=p.z}, false)
else else
n.level = minetest.env:get_node_level(p) n.level = core.env:get_node_level(p)
minetest.remove_node(p) core.remove_node(p)
spawn_falling_node(p, n) spawn_falling_node(p, n)
nodeupdate(p) nodeupdate(p)
end end
end end
end end
if minetest.get_item_group(n.name, "attached_node") ~= 0 then if core.get_item_group(n.name, "attached_node") ~= 0 then
if not check_attached_node(p, n) then if not check_attached_node(p, n) then
drop_attached_node(p) drop_attached_node(p)
nodeupdate(p) nodeupdate(p)
@ -209,9 +211,9 @@ end
function on_placenode(p, node) function on_placenode(p, node)
nodeupdate(p) nodeupdate(p)
end end
minetest.register_on_placenode(on_placenode) core.register_on_placenode(on_placenode)
function on_dignode(p, node) function on_dignode(p, node)
nodeupdate(p) nodeupdate(p)
end end
minetest.register_on_dignode(on_dignode) core.register_on_dignode(on_dignode)

@ -1,6 +1,6 @@
-- Minetest: builtin/features.lua -- Minetest: builtin/features.lua
minetest.features = { core.features = {
glasslike_framed = true, glasslike_framed = true,
nodebox_as_selectionbox = true, nodebox_as_selectionbox = true,
chat_send_player_param3 = true, chat_send_player_param3 = true,
@ -9,19 +9,19 @@ minetest.features = {
no_legacy_abms = true, no_legacy_abms = true,
} }
function minetest.has_feature(arg) function core.has_feature(arg)
if type(arg) == "table" then if type(arg) == "table" then
missing_features = {} missing_features = {}
result = true result = true
for ft, _ in pairs(arg) do for ft, _ in pairs(arg) do
if not minetest.features[ftr] then if not core.features[ftr] then
missing_features[ftr] = true missing_features[ftr] = true
result = false result = false
end end
end end
return result, missing_features return result, missing_features
elseif type(arg) == "string" then elseif type(arg) == "string" then
if not minetest.features[arg] then if not core.features[arg] then
return false, {[arg]=true} return false, {[arg]=true}
end end
return true, {} return true, {}

@ -1,8 +1,8 @@
-- Prevent anyone else accessing those functions -- Prevent anyone else accessing those functions
local forceload_block = minetest.forceload_block local forceload_block = core.forceload_block
local forceload_free_block = minetest.forceload_free_block local forceload_free_block = core.forceload_free_block
minetest.forceload_block = nil core.forceload_block = nil
minetest.forceload_free_block = nil core.forceload_free_block = nil
local blocks_forceloaded local blocks_forceloaded
local total_forceloaded = 0 local total_forceloaded = 0
@ -15,14 +15,14 @@ local function get_blockpos(pos)
z = math.floor(pos.z/BLOCKSIZE)} z = math.floor(pos.z/BLOCKSIZE)}
end end
function minetest.forceload_block(pos) function core.forceload_block(pos)
local blockpos = get_blockpos(pos) local blockpos = get_blockpos(pos)
local hash = minetest.hash_node_position(blockpos) local hash = core.hash_node_position(blockpos)
if blocks_forceloaded[hash] ~= nil then if blocks_forceloaded[hash] ~= nil then
blocks_forceloaded[hash] = blocks_forceloaded[hash] + 1 blocks_forceloaded[hash] = blocks_forceloaded[hash] + 1
return true return true
else else
if total_forceloaded >= (tonumber(minetest.setting_get("max_forceloaded_blocks")) or 16) then if total_forceloaded >= (tonumber(core.setting_get("max_forceloaded_blocks")) or 16) then
return false return false
end end
total_forceloaded = total_forceloaded+1 total_forceloaded = total_forceloaded+1
@ -32,9 +32,9 @@ function minetest.forceload_block(pos)
end end
end end
function minetest.forceload_free_block(pos) function core.forceload_free_block(pos)
local blockpos = get_blockpos(pos) local blockpos = get_blockpos(pos)
local hash = minetest.hash_node_position(blockpos) local hash = core.hash_node_position(blockpos)
if blocks_forceloaded[hash] == nil then return end if blocks_forceloaded[hash] == nil then return end
if blocks_forceloaded[hash] > 1 then if blocks_forceloaded[hash] > 1 then
blocks_forceloaded[hash] = blocks_forceloaded[hash] - 1 blocks_forceloaded[hash] = blocks_forceloaded[hash] - 1
@ -46,19 +46,19 @@ function minetest.forceload_free_block(pos)
end end
-- Keep the forceloaded areas after restart -- Keep the forceloaded areas after restart
local wpath = minetest.get_worldpath() local wpath = core.get_worldpath()
local function read_file(filename) local function read_file(filename)
local f = io.open(filename, "r") local f = io.open(filename, "r")
if f==nil then return {} end if f==nil then return {} end
local t = f:read("*all") local t = f:read("*all")
f:close() f:close()
if t=="" or t==nil then return {} end if t=="" or t==nil then return {} end
return minetest.deserialize(t) return core.deserialize(t)
end end
local function write_file(filename, table) local function write_file(filename, table)
local f = io.open(filename, "w") local f = io.open(filename, "w")
f:write(minetest.serialize(table)) f:write(core.serialize(table))
f:close() f:close()
end end
@ -67,13 +67,13 @@ for _, __ in pairs(blocks_forceloaded) do
total_forceloaded = total_forceloaded + 1 total_forceloaded = total_forceloaded + 1
end end
minetest.after(5, function() core.after(5, function()
for hash, _ in pairs(blocks_forceloaded) do for hash, _ in pairs(blocks_forceloaded) do
local blockpos = minetest.get_position_from_hash(hash) local blockpos = core.get_position_from_hash(hash)
forceload_block(blockpos) forceload_block(blockpos)
end end
end) end)
minetest.register_on_shutdown(function() core.register_on_shutdown(function()
write_file(wpath.."/force_loaded.txt", blocks_forceloaded) write_file(wpath.."/force_loaded.txt", blocks_forceloaded)
end) end)

@ -13,7 +13,7 @@ end
-- Item definition helpers -- Item definition helpers
-- --
function minetest.inventorycube(img1, img2, img3) function core.inventorycube(img1, img2, img3)
img2 = img2 or img1 img2 = img2 or img1
img3 = img3 or img1 img3 = img3 or img1
return "[inventorycube" return "[inventorycube"
@ -22,7 +22,7 @@ function minetest.inventorycube(img1, img2, img3)
.. "{" .. img3:gsub("%^", "&") .. "{" .. img3:gsub("%^", "&")
end end
function minetest.get_pointed_thing_position(pointed_thing, above) function core.get_pointed_thing_position(pointed_thing, above)
if pointed_thing.type == "node" then if pointed_thing.type == "node" then
if above then if above then
-- The position where a node would be placed -- The position where a node would be placed
@ -43,7 +43,7 @@ function minetest.get_pointed_thing_position(pointed_thing, above)
end end
end end
function minetest.dir_to_facedir(dir, is6d) function core.dir_to_facedir(dir, is6d)
--account for y if requested --account for y if requested
if is6d and math.abs(dir.y) > math.abs(dir.x) and math.abs(dir.y) > math.abs(dir.z) then if is6d and math.abs(dir.y) > math.abs(dir.x) and math.abs(dir.y) > math.abs(dir.z) then
@ -96,7 +96,7 @@ function minetest.dir_to_facedir(dir, is6d)
end end
end end
function minetest.facedir_to_dir(facedir) function core.facedir_to_dir(facedir)
--a table of possible dirs --a table of possible dirs
return ({{x=0, y=0, z=1}, return ({{x=0, y=0, z=1},
{x=1, y=0, z=0}, {x=1, y=0, z=0},
@ -117,7 +117,7 @@ function minetest.facedir_to_dir(facedir)
[facedir]] [facedir]]
end end
function minetest.dir_to_wallmounted(dir) function core.dir_to_wallmounted(dir)
if math.abs(dir.y) > math.max(math.abs(dir.x), math.abs(dir.z)) then if math.abs(dir.y) > math.max(math.abs(dir.x), math.abs(dir.z)) then
if dir.y < 0 then if dir.y < 0 then
return 1 return 1
@ -139,7 +139,7 @@ function minetest.dir_to_wallmounted(dir)
end end
end end
function minetest.get_node_drops(nodename, toolname) function core.get_node_drops(nodename, toolname)
local drop = ItemStack({name=nodename}):get_definition().drop local drop = ItemStack({name=nodename}):get_definition().drop
if drop == nil then if drop == nil then
-- default drop -- default drop
@ -188,7 +188,7 @@ function minetest.get_node_drops(nodename, toolname)
return got_items return got_items
end end
function minetest.item_place_node(itemstack, placer, pointed_thing, param2) function core.item_place_node(itemstack, placer, pointed_thing, param2)
local item = itemstack:peek_item() local item = itemstack:peek_item()
local def = itemstack:get_definition() local def = itemstack:get_definition()
if def.type ~= "node" or pointed_thing.type ~= "node" then if def.type ~= "node" or pointed_thing.type ~= "node" then
@ -196,24 +196,24 @@ function minetest.item_place_node(itemstack, placer, pointed_thing, param2)
end end
local under = pointed_thing.under local under = pointed_thing.under
local oldnode_under = minetest.get_node_or_nil(under) local oldnode_under = core.get_node_or_nil(under)
local above = pointed_thing.above local above = pointed_thing.above
local oldnode_above = minetest.get_node_or_nil(above) local oldnode_above = core.get_node_or_nil(above)
if not oldnode_under or not oldnode_above then if not oldnode_under or not oldnode_above then
minetest.log("info", placer:get_player_name() .. " tried to place" core.log("info", placer:get_player_name() .. " tried to place"
.. " node in unloaded position " .. minetest.pos_to_string(above)) .. " node in unloaded position " .. core.pos_to_string(above))
return itemstack, false return itemstack, false
end end
local olddef_under = ItemStack({name=oldnode_under.name}):get_definition() local olddef_under = ItemStack({name=oldnode_under.name}):get_definition()
olddef_under = olddef_under or minetest.nodedef_default olddef_under = olddef_under or core.nodedef_default
local olddef_above = ItemStack({name=oldnode_above.name}):get_definition() local olddef_above = ItemStack({name=oldnode_above.name}):get_definition()
olddef_above = olddef_above or minetest.nodedef_default olddef_above = olddef_above or core.nodedef_default
if not olddef_above.buildable_to and not olddef_under.buildable_to then if not olddef_above.buildable_to and not olddef_under.buildable_to then
minetest.log("info", placer:get_player_name() .. " tried to place" core.log("info", placer:get_player_name() .. " tried to place"
.. " node in invalid position " .. minetest.pos_to_string(above) .. " node in invalid position " .. core.pos_to_string(above)
.. ", replacing " .. oldnode_above.name) .. ", replacing " .. oldnode_above.name)
return itemstack, false return itemstack, false
end end
@ -223,23 +223,23 @@ function minetest.item_place_node(itemstack, placer, pointed_thing, param2)
-- If node under is buildable_to, place into it instead (eg. snow) -- If node under is buildable_to, place into it instead (eg. snow)
if olddef_under.buildable_to then if olddef_under.buildable_to then
minetest.log("info", "node under is buildable to") core.log("info", "node under is buildable to")
place_to = {x = under.x, y = under.y, z = under.z} place_to = {x = under.x, y = under.y, z = under.z}
end end
if minetest.is_protected(place_to, placer:get_player_name()) then if core.is_protected(place_to, placer:get_player_name()) then
minetest.log("action", placer:get_player_name() core.log("action", placer:get_player_name()
.. " tried to place " .. def.name .. " tried to place " .. def.name
.. " at protected position " .. " at protected position "
.. minetest.pos_to_string(place_to)) .. core.pos_to_string(place_to))
minetest.record_protection_violation(place_to, placer:get_player_name()) core.record_protection_violation(place_to, placer:get_player_name())
return itemstack return itemstack
end end
minetest.log("action", placer:get_player_name() .. " places node " core.log("action", placer:get_player_name() .. " places node "
.. def.name .. " at " .. minetest.pos_to_string(place_to)) .. def.name .. " at " .. core.pos_to_string(place_to))
local oldnode = minetest.get_node(place_to) local oldnode = core.get_node(place_to)
local newnode = {name = def.name, param1 = 0, param2 = param2} local newnode = {name = def.name, param1 = 0, param2 = param2}
-- Calculate direction for wall mounted stuff like torches and signs -- Calculate direction for wall mounted stuff like torches and signs
@ -249,7 +249,7 @@ function minetest.item_place_node(itemstack, placer, pointed_thing, param2)
y = under.y - above.y, y = under.y - above.y,
z = under.z - above.z z = under.z - above.z
} }
newnode.param2 = minetest.dir_to_wallmounted(dir) newnode.param2 = core.dir_to_wallmounted(dir)
-- Calculate the direction for furnaces and chests and stuff -- Calculate the direction for furnaces and chests and stuff
elseif def.paramtype2 == 'facedir' and not param2 then elseif def.paramtype2 == 'facedir' and not param2 then
local placer_pos = placer:getpos() local placer_pos = placer:getpos()
@ -259,21 +259,21 @@ function minetest.item_place_node(itemstack, placer, pointed_thing, param2)
y = above.y - placer_pos.y, y = above.y - placer_pos.y,
z = above.z - placer_pos.z z = above.z - placer_pos.z
} }
newnode.param2 = minetest.dir_to_facedir(dir) newnode.param2 = core.dir_to_facedir(dir)
minetest.log("action", "facedir: " .. newnode.param2) core.log("action", "facedir: " .. newnode.param2)
end end
end end
-- Check if the node is attached and if it can be placed there -- Check if the node is attached and if it can be placed there
if minetest.get_item_group(def.name, "attached_node") ~= 0 and if core.get_item_group(def.name, "attached_node") ~= 0 and
not check_attached_node(place_to, newnode) then not check_attached_node(place_to, newnode) then
minetest.log("action", "attached node " .. def.name .. core.log("action", "attached node " .. def.name ..
" can not be placed at " .. minetest.pos_to_string(place_to)) " can not be placed at " .. core.pos_to_string(place_to))
return itemstack, false return itemstack, false
end end
-- Add node and update -- Add node and update
minetest.add_node(place_to, newnode) core.add_node(place_to, newnode)
local take_item = true local take_item = true
@ -290,7 +290,7 @@ function minetest.item_place_node(itemstack, placer, pointed_thing, param2)
-- Run script hook -- Run script hook
local _, callback local _, callback
for _, callback in ipairs(minetest.registered_on_placenodes) do for _, callback in ipairs(core.registered_on_placenodes) do
-- Deepcopy pos, node and pointed_thing because callback can modify them -- Deepcopy pos, node and pointed_thing because callback can modify them
local place_to_copy = {x=place_to.x, y=place_to.y, z=place_to.z} local place_to_copy = {x=place_to.x, y=place_to.y, z=place_to.z}
local newnode_copy = {name=newnode.name, param1=newnode.param1, param2=newnode.param2} local newnode_copy = {name=newnode.name, param1=newnode.param1, param2=newnode.param2}
@ -307,38 +307,38 @@ function minetest.item_place_node(itemstack, placer, pointed_thing, param2)
return itemstack, true return itemstack, true
end end
function minetest.item_place_object(itemstack, placer, pointed_thing) function core.item_place_object(itemstack, placer, pointed_thing)
local pos = minetest.get_pointed_thing_position(pointed_thing, true) local pos = core.get_pointed_thing_position(pointed_thing, true)
if pos ~= nil then if pos ~= nil then
local item = itemstack:take_item() local item = itemstack:take_item()
minetest.add_item(pos, item) core.add_item(pos, item)
end end
return itemstack return itemstack
end end
function minetest.item_place(itemstack, placer, pointed_thing, param2) function core.item_place(itemstack, placer, pointed_thing, param2)
-- Call on_rightclick if the pointed node defines it -- Call on_rightclick if the pointed node defines it
if pointed_thing.type == "node" and placer and if pointed_thing.type == "node" and placer and
not placer:get_player_control().sneak then not placer:get_player_control().sneak then
local n = minetest.get_node(pointed_thing.under) local n = core.get_node(pointed_thing.under)
local nn = n.name local nn = n.name
if minetest.registered_nodes[nn] and minetest.registered_nodes[nn].on_rightclick then if core.registered_nodes[nn] and core.registered_nodes[nn].on_rightclick then
return minetest.registered_nodes[nn].on_rightclick(pointed_thing.under, n, return core.registered_nodes[nn].on_rightclick(pointed_thing.under, n,
placer, itemstack, pointed_thing) or itemstack, false placer, itemstack, pointed_thing) or itemstack, false
end end
end end
if itemstack:get_definition().type == "node" then if itemstack:get_definition().type == "node" then
return minetest.item_place_node(itemstack, placer, pointed_thing, param2) return core.item_place_node(itemstack, placer, pointed_thing, param2)
end end
return itemstack return itemstack
end end
function minetest.item_drop(itemstack, dropper, pos) function core.item_drop(itemstack, dropper, pos)
if dropper.get_player_name then if dropper.get_player_name then
local v = dropper:get_look_dir() local v = dropper:get_look_dir()
local p = {x=pos.x+v.x, y=pos.y+1.5+v.y, z=pos.z+v.z} local p = {x=pos.x+v.x, y=pos.y+1.5+v.y, z=pos.z+v.z}
local obj = minetest.add_item(p, itemstack) local obj = core.add_item(p, itemstack)
if obj then if obj then
v.x = v.x*2 v.x = v.x*2
v.y = v.y*2 + 1 v.y = v.y*2 + 1
@ -346,12 +346,12 @@ function minetest.item_drop(itemstack, dropper, pos)
obj:setvelocity(v) obj:setvelocity(v)
end end
else else
minetest.add_item(pos, itemstack) core.add_item(pos, itemstack)
end end
return ItemStack("") return ItemStack("")
end end
function minetest.item_eat(hp_change, replace_with_item) function core.item_eat(hp_change, replace_with_item)
return function(itemstack, user, pointed_thing) -- closure return function(itemstack, user, pointed_thing) -- closure
if itemstack:take_item() ~= nil then if itemstack:take_item() ~= nil then
user:set_hp(user:get_hp() + hp_change) user:set_hp(user:get_hp() + hp_change)
@ -361,9 +361,9 @@ function minetest.item_eat(hp_change, replace_with_item)
end end
end end
function minetest.node_punch(pos, node, puncher, pointed_thing) function core.node_punch(pos, node, puncher, pointed_thing)
-- Run script hook -- Run script hook
for _, callback in ipairs(minetest.registered_on_punchnodes) do for _, callback in ipairs(core.registered_on_punchnodes) do
-- Copy pos and node because callback can modify them -- Copy pos and node because callback can modify them
local pos_copy = vector.new(pos) local pos_copy = vector.new(pos)
local node_copy = {name=node.name, param1=node.param1, param2=node.param2} local node_copy = {name=node.name, param1=node.param1, param2=node.param2}
@ -372,7 +372,7 @@ function minetest.node_punch(pos, node, puncher, pointed_thing)
end end
end end
function minetest.handle_node_drops(pos, drops, digger) function core.handle_node_drops(pos, drops, digger)
-- Add dropped items to object's inventory -- Add dropped items to object's inventory
if digger:get_inventory() then if digger:get_inventory() then
local _, dropped_item local _, dropped_item
@ -384,59 +384,59 @@ function minetest.handle_node_drops(pos, drops, digger)
y = pos.y + math.random()/2-0.25, y = pos.y + math.random()/2-0.25,
z = pos.z + math.random()/2-0.25, z = pos.z + math.random()/2-0.25,
} }
minetest.add_item(p, left) core.add_item(p, left)
end end
end end
end end
end end
function minetest.node_dig(pos, node, digger) function core.node_dig(pos, node, digger)
local def = ItemStack({name=node.name}):get_definition() local def = ItemStack({name=node.name}):get_definition()
if not def.diggable or (def.can_dig and not def.can_dig(pos,digger)) then if not def.diggable or (def.can_dig and not def.can_dig(pos,digger)) then
minetest.log("info", digger:get_player_name() .. " tried to dig " core.log("info", digger:get_player_name() .. " tried to dig "
.. node.name .. " which is not diggable " .. node.name .. " which is not diggable "
.. minetest.pos_to_string(pos)) .. core.pos_to_string(pos))
return return
end end
if minetest.is_protected(pos, digger:get_player_name()) then if core.is_protected(pos, digger:get_player_name()) then
minetest.log("action", digger:get_player_name() core.log("action", digger:get_player_name()
.. " tried to dig " .. node.name .. " tried to dig " .. node.name
.. " at protected position " .. " at protected position "
.. minetest.pos_to_string(pos)) .. core.pos_to_string(pos))
minetest.record_protection_violation(pos, digger:get_player_name()) core.record_protection_violation(pos, digger:get_player_name())
return return
end end
minetest.log('action', digger:get_player_name() .. " digs " core.log('action', digger:get_player_name() .. " digs "
.. node.name .. " at " .. minetest.pos_to_string(pos)) .. node.name .. " at " .. core.pos_to_string(pos))
local wielded = digger:get_wielded_item() local wielded = digger:get_wielded_item()
local drops = minetest.get_node_drops(node.name, wielded:get_name()) local drops = core.get_node_drops(node.name, wielded:get_name())
local wdef = wielded:get_definition() local wdef = wielded:get_definition()
local tp = wielded:get_tool_capabilities() local tp = wielded:get_tool_capabilities()
local dp = minetest.get_dig_params(def.groups, tp) local dp = core.get_dig_params(def.groups, tp)
if wdef and wdef.after_use then if wdef and wdef.after_use then
wielded = wdef.after_use(wielded, digger, node, dp) or wielded wielded = wdef.after_use(wielded, digger, node, dp) or wielded
else else
-- Wear out tool -- Wear out tool
if not minetest.setting_getbool("creative_mode") then if not core.setting_getbool("creative_mode") then
wielded:add_wear(dp.wear) wielded:add_wear(dp.wear)
end end
end end
digger:set_wielded_item(wielded) digger:set_wielded_item(wielded)
-- Handle drops -- Handle drops
minetest.handle_node_drops(pos, drops, digger) core.handle_node_drops(pos, drops, digger)
local oldmetadata = nil local oldmetadata = nil
if def.after_dig_node then if def.after_dig_node then
oldmetadata = minetest.get_meta(pos):to_table() oldmetadata = core.get_meta(pos):to_table()
end end
-- Remove node and update -- Remove node and update
minetest.remove_node(pos) core.remove_node(pos)
-- Run callback -- Run callback
if def.after_dig_node then if def.after_dig_node then
@ -448,7 +448,7 @@ function minetest.node_dig(pos, node, digger)
-- Run script hook -- Run script hook
local _, callback local _, callback
for _, callback in ipairs(minetest.registered_on_dignodes) do for _, callback in ipairs(core.registered_on_dignodes) do
-- Copy pos and node because callback can modify them -- Copy pos and node because callback can modify them
local pos_copy = {x=pos.x, y=pos.y, z=pos.z} local pos_copy = {x=pos.x, y=pos.y, z=pos.z}
local node_copy = {name=node.name, param1=node.param1, param2=node.param2} local node_copy = {name=node.name, param1=node.param1, param2=node.param2}
@ -456,7 +456,7 @@ function minetest.node_dig(pos, node, digger)
end end
end end
-- This is used to allow mods to redefine minetest.item_place and so on -- This is used to allow mods to redefine core.item_place and so on
-- NOTE: This is not the preferred way. Preferred way is to provide enough -- NOTE: This is not the preferred way. Preferred way is to provide enough
-- callbacks to not require redefining global functions. -celeron55 -- callbacks to not require redefining global functions. -celeron55
local function redef_wrapper(table, name) local function redef_wrapper(table, name)
@ -469,7 +469,7 @@ end
-- Item definition defaults -- Item definition defaults
-- --
minetest.nodedef_default = { core.nodedef_default = {
-- Item properties -- Item properties
type="node", type="node",
-- name intentionally not defined here -- name intentionally not defined here
@ -485,20 +485,20 @@ minetest.nodedef_default = {
node_placement_prediction = nil, node_placement_prediction = nil,
-- Interaction callbacks -- Interaction callbacks
on_place = redef_wrapper(minetest, 'item_place'), -- minetest.item_place on_place = redef_wrapper(core, 'item_place'), -- core.item_place
on_drop = redef_wrapper(minetest, 'item_drop'), -- minetest.item_drop on_drop = redef_wrapper(core, 'item_drop'), -- core.item_drop
on_use = nil, on_use = nil,
can_dig = nil, can_dig = nil,
on_punch = redef_wrapper(minetest, 'node_punch'), -- minetest.node_punch on_punch = redef_wrapper(core, 'node_punch'), -- core.node_punch
on_rightclick = nil, on_rightclick = nil,
on_dig = redef_wrapper(minetest, 'node_dig'), -- minetest.node_dig on_dig = redef_wrapper(core, 'node_dig'), -- core.node_dig
on_receive_fields = nil, on_receive_fields = nil,
on_metadata_inventory_move = minetest.node_metadata_inventory_move_allow_all, on_metadata_inventory_move = core.node_metadata_inventory_move_allow_all,
on_metadata_inventory_offer = minetest.node_metadata_inventory_offer_allow_all, on_metadata_inventory_offer = core.node_metadata_inventory_offer_allow_all,
on_metadata_inventory_take = minetest.node_metadata_inventory_take_allow_all, on_metadata_inventory_take = core.node_metadata_inventory_take_allow_all,
-- Node properties -- Node properties
drawtype = "normal", drawtype = "normal",
@ -533,7 +533,7 @@ minetest.nodedef_default = {
legacy_wallmounted = false, legacy_wallmounted = false,
} }
minetest.craftitemdef_default = { core.craftitemdef_default = {
type="craft", type="craft",
-- name intentionally not defined here -- name intentionally not defined here
description = "", description = "",
@ -546,12 +546,12 @@ minetest.craftitemdef_default = {
tool_capabilities = nil, tool_capabilities = nil,
-- Interaction callbacks -- Interaction callbacks
on_place = redef_wrapper(minetest, 'item_place'), -- minetest.item_place on_place = redef_wrapper(core, 'item_place'), -- core.item_place
on_drop = redef_wrapper(minetest, 'item_drop'), -- minetest.item_drop on_drop = redef_wrapper(core, 'item_drop'), -- core.item_drop
on_use = nil, on_use = nil,
} }
minetest.tooldef_default = { core.tooldef_default = {
type="tool", type="tool",
-- name intentionally not defined here -- name intentionally not defined here
description = "", description = "",
@ -564,12 +564,12 @@ minetest.tooldef_default = {
tool_capabilities = nil, tool_capabilities = nil,
-- Interaction callbacks -- Interaction callbacks
on_place = redef_wrapper(minetest, 'item_place'), -- minetest.item_place on_place = redef_wrapper(core, 'item_place'), -- core.item_place
on_drop = redef_wrapper(minetest, 'item_drop'), -- minetest.item_drop on_drop = redef_wrapper(core, 'item_drop'), -- core.item_drop
on_use = nil, on_use = nil,
} }
minetest.noneitemdef_default = { -- This is used for the hand and unknown items core.noneitemdef_default = { -- This is used for the hand and unknown items
type="none", type="none",
-- name intentionally not defined here -- name intentionally not defined here
description = "", description = "",
@ -582,7 +582,7 @@ minetest.noneitemdef_default = { -- This is used for the hand and unknown items
tool_capabilities = nil, tool_capabilities = nil,
-- Interaction callbacks -- Interaction callbacks
on_place = redef_wrapper(minetest, 'item_place'), on_place = redef_wrapper(core, 'item_place'),
on_drop = nil, on_drop = nil,
on_use = nil, on_use = nil,
} }

@ -1,14 +1,14 @@
-- Minetest: builtin/item_entity.lua -- Minetest: builtin/item_entity.lua
function minetest.spawn_item(pos, item) function core.spawn_item(pos, item)
-- Take item in any format -- Take item in any format
local stack = ItemStack(item) local stack = ItemStack(item)
local obj = minetest.add_entity(pos, "__builtin:item") local obj = core.add_entity(pos, "__builtin:item")
obj:get_luaentity():set_item(stack:to_string()) obj:get_luaentity():set_item(stack:to_string())
return obj return obj
end end
minetest.register_entity(":__builtin:item", { core.register_entity(":__builtin:item", {
initial_properties = { initial_properties = {
hp_max = 1, hp_max = 1,
physical = true, physical = true,
@ -35,9 +35,9 @@ minetest.register_entity(":__builtin:item", {
end end
local item_texture = nil local item_texture = nil
local item_type = "" local item_type = ""
if minetest.registered_items[itemname] then if core.registered_items[itemname] then
item_texture = minetest.registered_items[itemname].inventory_image item_texture = core.registered_items[itemname].inventory_image
item_type = minetest.registered_items[itemname].type item_type = core.registered_items[itemname].type
end end
prop = { prop = {
is_visible = true, is_visible = true,
@ -59,7 +59,7 @@ minetest.register_entity(":__builtin:item", {
get_staticdata = function(self) get_staticdata = function(self)
--return self.itemstring --return self.itemstring
return minetest.serialize({ return core.serialize({
itemstring = self.itemstring, itemstring = self.itemstring,
always_collect = self.always_collect, always_collect = self.always_collect,
}) })
@ -67,7 +67,7 @@ minetest.register_entity(":__builtin:item", {
on_activate = function(self, staticdata) on_activate = function(self, staticdata)
if string.sub(staticdata, 1, string.len("return")) == "return" then if string.sub(staticdata, 1, string.len("return")) == "return" then
local data = minetest.deserialize(staticdata) local data = core.deserialize(staticdata)
if data and type(data) == "table" then if data and type(data) == "table" then
self.itemstring = data.itemstring self.itemstring = data.itemstring
self.always_collect = data.always_collect self.always_collect = data.always_collect
@ -84,10 +84,10 @@ minetest.register_entity(":__builtin:item", {
on_step = function(self, dtime) on_step = function(self, dtime)
local p = self.object:getpos() local p = self.object:getpos()
p.y = p.y - 0.3 p.y = p.y - 0.3
local nn = minetest.get_node(p).name local nn = core.get_node(p).name
-- If node is not registered or node is walkably solid and resting on nodebox -- If node is not registered or node is walkably solid and resting on nodebox
local v = self.object:getvelocity() local v = self.object:getvelocity()
if not minetest.registered_nodes[nn] or minetest.registered_nodes[nn].walkable and v.y == 0 then if not core.registered_nodes[nn] or core.registered_nodes[nn].walkable and v.y == 0 then
if self.physical_state then if self.physical_state then
self.object:setvelocity({x=0,y=0,z=0}) self.object:setvelocity({x=0,y=0,z=0})
self.object:setacceleration({x=0, y=0, z=0}) self.object:setacceleration({x=0, y=0, z=0})

@ -4,30 +4,30 @@
-- Misc. API functions -- Misc. API functions
-- --
minetest.timers_to_add = {} core.timers_to_add = {}
minetest.timers = {} core.timers = {}
minetest.register_globalstep(function(dtime) core.register_globalstep(function(dtime)
for _, timer in ipairs(minetest.timers_to_add) do for _, timer in ipairs(core.timers_to_add) do
table.insert(minetest.timers, timer) table.insert(core.timers, timer)
end end
minetest.timers_to_add = {} core.timers_to_add = {}
for index, timer in ipairs(minetest.timers) do for index, timer in ipairs(core.timers) do
timer.time = timer.time - dtime timer.time = timer.time - dtime
if timer.time <= 0 then if timer.time <= 0 then
timer.func(unpack(timer.args or {})) timer.func(unpack(timer.args or {}))
table.remove(minetest.timers,index) table.remove(core.timers,index)
end end
end end
end) end)
function minetest.after(time, func, ...) function core.after(time, func, ...)
assert(tonumber(time) and type(func) == "function", assert(tonumber(time) and type(func) == "function",
"Invalid minetest.after invocation") "Invalid core.after invocation")
table.insert(minetest.timers_to_add, {time=time, func=func, args={...}}) table.insert(core.timers_to_add, {time=time, func=func, args={...}})
end end
function minetest.check_player_privs(name, privs) function core.check_player_privs(name, privs)
local player_privs = minetest.get_player_privs(name) local player_privs = core.get_player_privs(name)
local missing_privileges = {} local missing_privileges = {}
for priv, val in pairs(privs) do for priv, val in pairs(privs) do
if val then if val then
@ -44,15 +44,15 @@ end
local player_list = {} local player_list = {}
minetest.register_on_joinplayer(function(player) core.register_on_joinplayer(function(player)
player_list[player:get_player_name()] = player player_list[player:get_player_name()] = player
end) end)
minetest.register_on_leaveplayer(function(player) core.register_on_leaveplayer(function(player)
player_list[player:get_player_name()] = nil player_list[player:get_player_name()] = nil
end) end)
function minetest.get_connected_players() function core.get_connected_players()
local temp_table = {} local temp_table = {}
for index, value in pairs(player_list) do for index, value in pairs(player_list) do
if value:is_player_connected() then if value:is_player_connected() then
@ -62,11 +62,11 @@ function minetest.get_connected_players()
return temp_table return temp_table
end end
function minetest.hash_node_position(pos) function core.hash_node_position(pos)
return (pos.z+32768)*65536*65536 + (pos.y+32768)*65536 + pos.x+32768 return (pos.z+32768)*65536*65536 + (pos.y+32768)*65536 + pos.x+32768
end end
function minetest.get_position_from_hash(hash) function core.get_position_from_hash(hash)
local pos = {} local pos = {}
pos.x = (hash%65536) - 32768 pos.x = (hash%65536) - 32768
hash = math.floor(hash/65536) hash = math.floor(hash/65536)
@ -76,20 +76,20 @@ function minetest.get_position_from_hash(hash)
return pos return pos
end end
function minetest.get_item_group(name, group) function core.get_item_group(name, group)
if not minetest.registered_items[name] or not if not core.registered_items[name] or not
minetest.registered_items[name].groups[group] then core.registered_items[name].groups[group] then
return 0 return 0
end end
return minetest.registered_items[name].groups[group] return core.registered_items[name].groups[group]
end end
function minetest.get_node_group(name, group) function core.get_node_group(name, group)
minetest.log("deprecated", "Deprecated usage of get_node_group, use get_item_group instead") core.log("deprecated", "Deprecated usage of get_node_group, use get_item_group instead")
return minetest.get_item_group(name, group) return core.get_item_group(name, group)
end end
function minetest.string_to_pos(value) function core.string_to_pos(value)
local p = {} local p = {}
p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$") p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
if p.x and p.y and p.z then if p.x and p.y and p.z then
@ -109,25 +109,25 @@ function minetest.string_to_pos(value)
return nil return nil
end end
assert(minetest.string_to_pos("10.0, 5, -2").x == 10) assert(core.string_to_pos("10.0, 5, -2").x == 10)
assert(minetest.string_to_pos("( 10.0, 5, -2)").z == -2) assert(core.string_to_pos("( 10.0, 5, -2)").z == -2)
assert(minetest.string_to_pos("asd, 5, -2)") == nil) assert(core.string_to_pos("asd, 5, -2)") == nil)
function minetest.setting_get_pos(name) function core.setting_get_pos(name)
local value = minetest.setting_get(name) local value = core.setting_get(name)
if not value then if not value then
return nil return nil
end end
return minetest.string_to_pos(value) return core.string_to_pos(value)
end end
-- To be overriden by protection mods -- To be overriden by protection mods
function minetest.is_protected(pos, name) function core.is_protected(pos, name)
return false return false
end end
function minetest.record_protection_violation(pos, name) function core.record_protection_violation(pos, name)
for _, func in pairs(minetest.registered_on_protection_violation) do for _, func in pairs(core.registered_on_protection_violation) do
func(pos, name) func(pos, name)
end end
end end

@ -4,9 +4,9 @@
-- Privileges -- Privileges
-- --
minetest.registered_privileges = {} core.registered_privileges = {}
function minetest.register_privilege(name, param) function core.register_privilege(name, param)
local function fill_defaults(def) local function fill_defaults(def)
if def.give_to_singleplayer == nil then if def.give_to_singleplayer == nil then
def.give_to_singleplayer = true def.give_to_singleplayer = true
@ -22,32 +22,32 @@ function minetest.register_privilege(name, param)
def = {description = param} def = {description = param}
end end
fill_defaults(def) fill_defaults(def)
minetest.registered_privileges[name] = def core.registered_privileges[name] = def
end end
minetest.register_privilege("interact", "Can interact with things and modify the world") core.register_privilege("interact", "Can interact with things and modify the world")
minetest.register_privilege("teleport", "Can use /teleport command") core.register_privilege("teleport", "Can use /teleport command")
minetest.register_privilege("bring", "Can teleport other players") core.register_privilege("bring", "Can teleport other players")
minetest.register_privilege("settime", "Can use /time") core.register_privilege("settime", "Can use /time")
minetest.register_privilege("privs", "Can modify privileges") core.register_privilege("privs", "Can modify privileges")
minetest.register_privilege("basic_privs", "Can modify 'shout' and 'interact' privileges") core.register_privilege("basic_privs", "Can modify 'shout' and 'interact' privileges")
minetest.register_privilege("server", "Can do server maintenance stuff") core.register_privilege("server", "Can do server maintenance stuff")
minetest.register_privilege("shout", "Can speak in chat") core.register_privilege("shout", "Can speak in chat")
minetest.register_privilege("ban", "Can ban and unban players") core.register_privilege("ban", "Can ban and unban players")
minetest.register_privilege("kick", "Can kick players") core.register_privilege("kick", "Can kick players")
minetest.register_privilege("give", "Can use /give and /giveme") core.register_privilege("give", "Can use /give and /giveme")
minetest.register_privilege("password", "Can use /setpassword and /clearpassword") core.register_privilege("password", "Can use /setpassword and /clearpassword")
minetest.register_privilege("fly", { core.register_privilege("fly", {
description = "Can fly using the free_move mode", description = "Can fly using the free_move mode",
give_to_singleplayer = false, give_to_singleplayer = false,
}) })
minetest.register_privilege("fast", { core.register_privilege("fast", {
description = "Can walk fast using the fast_move mode", description = "Can walk fast using the fast_move mode",
give_to_singleplayer = false, give_to_singleplayer = false,
}) })
minetest.register_privilege("noclip", { core.register_privilege("noclip", {
description = "Can fly through walls", description = "Can fly through walls",
give_to_singleplayer = false, give_to_singleplayer = false,
}) })
minetest.register_privilege("rollback", "Can use the rollback functionality") core.register_privilege("rollback", "Can use the rollback functionality")

@ -4,35 +4,35 @@
-- Make raw registration functions inaccessible to anyone except this file -- Make raw registration functions inaccessible to anyone except this file
-- --
local register_item_raw = minetest.register_item_raw local register_item_raw = core.register_item_raw
minetest.register_item_raw = nil core.register_item_raw = nil
local register_alias_raw = minetest.register_alias_raw local register_alias_raw = core.register_alias_raw
minetest.register_item_raw = nil core.register_item_raw = nil
-- --
-- Item / entity / ABM registration functions -- Item / entity / ABM registration functions
-- --
minetest.registered_abms = {} core.registered_abms = {}
minetest.registered_entities = {} core.registered_entities = {}
minetest.registered_items = {} core.registered_items = {}
minetest.registered_nodes = {} core.registered_nodes = {}
minetest.registered_craftitems = {} core.registered_craftitems = {}
minetest.registered_tools = {} core.registered_tools = {}
minetest.registered_aliases = {} core.registered_aliases = {}
-- For tables that are indexed by item name: -- For tables that are indexed by item name:
-- If table[X] does not exist, default to table[minetest.registered_aliases[X]] -- If table[X] does not exist, default to table[core.registered_aliases[X]]
local alias_metatable = { local alias_metatable = {
__index = function(t, name) __index = function(t, name)
return rawget(t, minetest.registered_aliases[name]) return rawget(t, core.registered_aliases[name])
end end
} }
setmetatable(minetest.registered_items, alias_metatable) setmetatable(core.registered_items, alias_metatable)
setmetatable(minetest.registered_nodes, alias_metatable) setmetatable(core.registered_nodes, alias_metatable)
setmetatable(minetest.registered_craftitems, alias_metatable) setmetatable(core.registered_craftitems, alias_metatable)
setmetatable(minetest.registered_tools, alias_metatable) setmetatable(core.registered_tools, alias_metatable)
-- These item names may not be used because they would interfere -- These item names may not be used because they would interfere
-- with legacy itemstrings -- with legacy itemstrings
@ -55,7 +55,7 @@ local function check_modname_prefix(name)
return name:sub(2) return name:sub(2)
else else
-- Modname prefix enforcement -- Modname prefix enforcement
local expected_prefix = minetest.get_current_modname() .. ":" local expected_prefix = core.get_current_modname() .. ":"
if name:sub(1, #expected_prefix) ~= expected_prefix then if name:sub(1, #expected_prefix) ~= expected_prefix then
error("Name " .. name .. " does not follow naming conventions: " .. error("Name " .. name .. " does not follow naming conventions: " ..
"\"modname:\" or \":\" prefix required") "\"modname:\" or \":\" prefix required")
@ -69,12 +69,12 @@ local function check_modname_prefix(name)
end end
end end
function minetest.register_abm(spec) function core.register_abm(spec)
-- Add to minetest.registered_abms -- Add to core.registered_abms
minetest.registered_abms[#minetest.registered_abms+1] = spec core.registered_abms[#core.registered_abms+1] = spec
end end
function minetest.register_entity(name, prototype) function core.register_entity(name, prototype)
-- Check name -- Check name
if name == nil then if name == nil then
error("Unable to register entity: Name is nil") error("Unable to register entity: Name is nil")
@ -84,11 +84,11 @@ function minetest.register_entity(name, prototype)
prototype.name = name prototype.name = name
prototype.__index = prototype -- so that it can be used as a metatable prototype.__index = prototype -- so that it can be used as a metatable
-- Add to minetest.registered_entities -- Add to core.registered_entities
minetest.registered_entities[name] = prototype core.registered_entities[name] = prototype
end end
function minetest.register_item(name, itemdef) function core.register_item(name, itemdef)
-- Check name -- Check name
if name == nil then if name == nil then
error("Unable to register item: Name is nil") error("Unable to register item: Name is nil")
@ -110,16 +110,16 @@ function minetest.register_item(name, itemdef)
fixed = {-1/8, -1/2, -1/8, 1/8, 1/2, 1/8}, fixed = {-1/8, -1/2, -1/8, 1/8, 1/2, 1/8},
} }
end end
setmetatable(itemdef, {__index = minetest.nodedef_default}) setmetatable(itemdef, {__index = core.nodedef_default})
minetest.registered_nodes[itemdef.name] = itemdef core.registered_nodes[itemdef.name] = itemdef
elseif itemdef.type == "craft" then elseif itemdef.type == "craft" then
setmetatable(itemdef, {__index = minetest.craftitemdef_default}) setmetatable(itemdef, {__index = core.craftitemdef_default})
minetest.registered_craftitems[itemdef.name] = itemdef core.registered_craftitems[itemdef.name] = itemdef
elseif itemdef.type == "tool" then elseif itemdef.type == "tool" then
setmetatable(itemdef, {__index = minetest.tooldef_default}) setmetatable(itemdef, {__index = core.tooldef_default})
minetest.registered_tools[itemdef.name] = itemdef core.registered_tools[itemdef.name] = itemdef
elseif itemdef.type == "none" then elseif itemdef.type == "none" then
setmetatable(itemdef, {__index = minetest.noneitemdef_default}) setmetatable(itemdef, {__index = core.noneitemdef_default})
else else
error("Unable to register item: Type is invalid: " .. dump(itemdef)) error("Unable to register item: Type is invalid: " .. dump(itemdef))
end end
@ -131,7 +131,7 @@ function minetest.register_item(name, itemdef)
-- BEGIN Legacy stuff -- BEGIN Legacy stuff
if itemdef.cookresult_itemstring ~= nil and itemdef.cookresult_itemstring ~= "" then if itemdef.cookresult_itemstring ~= nil and itemdef.cookresult_itemstring ~= "" then
minetest.register_craft({ core.register_craft({
type="cooking", type="cooking",
output=itemdef.cookresult_itemstring, output=itemdef.cookresult_itemstring,
recipe=itemdef.name, recipe=itemdef.name,
@ -139,7 +139,7 @@ function minetest.register_item(name, itemdef)
}) })
end end
if itemdef.furnace_burntime ~= nil and itemdef.furnace_burntime >= 0 then if itemdef.furnace_burntime ~= nil and itemdef.furnace_burntime >= 0 then
minetest.register_craft({ core.register_craft({
type="fuel", type="fuel",
recipe=itemdef.name, recipe=itemdef.name,
burntime=itemdef.furnace_burntime burntime=itemdef.furnace_burntime
@ -150,18 +150,18 @@ function minetest.register_item(name, itemdef)
-- Disable all further modifications -- Disable all further modifications
getmetatable(itemdef).__newindex = {} getmetatable(itemdef).__newindex = {}
--minetest.log("Registering item: " .. itemdef.name) --core.log("Registering item: " .. itemdef.name)
minetest.registered_items[itemdef.name] = itemdef core.registered_items[itemdef.name] = itemdef
minetest.registered_aliases[itemdef.name] = nil core.registered_aliases[itemdef.name] = nil
register_item_raw(itemdef) register_item_raw(itemdef)
end end
function minetest.register_node(name, nodedef) function core.register_node(name, nodedef)
nodedef.type = "node" nodedef.type = "node"
minetest.register_item(name, nodedef) core.register_item(name, nodedef)
end end
function minetest.register_craftitem(name, craftitemdef) function core.register_craftitem(name, craftitemdef)
craftitemdef.type = "craft" craftitemdef.type = "craft"
-- BEGIN Legacy stuff -- BEGIN Legacy stuff
@ -170,10 +170,10 @@ function minetest.register_craftitem(name, craftitemdef)
end end
-- END Legacy stuff -- END Legacy stuff
minetest.register_item(name, craftitemdef) core.register_item(name, craftitemdef)
end end
function minetest.register_tool(name, tooldef) function core.register_tool(name, tooldef)
tooldef.type = "tool" tooldef.type = "tool"
tooldef.stack_max = 1 tooldef.stack_max = 1
@ -209,39 +209,39 @@ function minetest.register_tool(name, tooldef)
end end
-- END Legacy stuff -- END Legacy stuff
minetest.register_item(name, tooldef) core.register_item(name, tooldef)
end end
function minetest.register_alias(name, convert_to) function core.register_alias(name, convert_to)
if forbidden_item_names[name] then if forbidden_item_names[name] then
error("Unable to register alias: Name is forbidden: " .. name) error("Unable to register alias: Name is forbidden: " .. name)
end end
if minetest.registered_items[name] ~= nil then if core.registered_items[name] ~= nil then
minetest.log("WARNING: Not registering alias, item with same name" .. core.log("WARNING: Not registering alias, item with same name" ..
" is already defined: " .. name .. " -> " .. convert_to) " is already defined: " .. name .. " -> " .. convert_to)
else else
--minetest.log("Registering alias: " .. name .. " -> " .. convert_to) --core.log("Registering alias: " .. name .. " -> " .. convert_to)
minetest.registered_aliases[name] = convert_to core.registered_aliases[name] = convert_to
register_alias_raw(name, convert_to) register_alias_raw(name, convert_to)
end end
end end
local register_biome_raw = minetest.register_biome local register_biome_raw = core.register_biome
minetest.registered_biomes = {} core.registered_biomes = {}
function minetest.register_biome(biome) function core.register_biome(biome)
minetest.registered_biomes[biome.name] = biome core.registered_biomes[biome.name] = biome
register_biome_raw(biome) register_biome_raw(biome)
end end
function minetest.on_craft(itemstack, player, old_craft_list, craft_inv) function core.on_craft(itemstack, player, old_craft_list, craft_inv)
for _, func in ipairs(minetest.registered_on_crafts) do for _, func in ipairs(core.registered_on_crafts) do
itemstack = func(itemstack, player, old_craft_list, craft_inv) or itemstack itemstack = func(itemstack, player, old_craft_list, craft_inv) or itemstack
end end
return itemstack return itemstack
end end
function minetest.craft_predict(itemstack, player, old_craft_list, craft_inv) function core.craft_predict(itemstack, player, old_craft_list, craft_inv)
for _, func in ipairs(minetest.registered_craft_predicts) do for _, func in ipairs(core.registered_craft_predicts) do
itemstack = func(itemstack, player, old_craft_list, craft_inv) or itemstack itemstack = func(itemstack, player, old_craft_list, craft_inv) or itemstack
end end
return itemstack return itemstack
@ -251,32 +251,32 @@ end
-- created via itemstrings (e.g. /give) -- created via itemstrings (e.g. /give)
local name local name
for name in pairs(forbidden_item_names) do for name in pairs(forbidden_item_names) do
minetest.registered_aliases[name] = "" core.registered_aliases[name] = ""
register_alias_raw(name, "") register_alias_raw(name, "")
end end
-- Deprecated: -- Deprecated:
-- Aliases for minetest.register_alias (how ironic...) -- Aliases for core.register_alias (how ironic...)
--minetest.alias_node = minetest.register_alias --core.alias_node = core.register_alias
--minetest.alias_tool = minetest.register_alias --core.alias_tool = core.register_alias
--minetest.alias_craftitem = minetest.register_alias --core.alias_craftitem = core.register_alias
-- --
-- Built-in node definitions. Also defined in C. -- Built-in node definitions. Also defined in C.
-- --
minetest.register_item(":unknown", { core.register_item(":unknown", {
type = "none", type = "none",
description = "Unknown Item", description = "Unknown Item",
inventory_image = "unknown_item.png", inventory_image = "unknown_item.png",
on_place = minetest.item_place, on_place = core.item_place,
on_drop = minetest.item_drop, on_drop = core.item_drop,
groups = {not_in_creative_inventory=1}, groups = {not_in_creative_inventory=1},
diggable = true, diggable = true,
}) })
minetest.register_node(":air", { core.register_node(":air", {
description = "Air (you hacker you!)", description = "Air (you hacker you!)",
inventory_image = "unknown_node.png", inventory_image = "unknown_node.png",
wield_image = "unknown_node.png", wield_image = "unknown_node.png",
@ -292,7 +292,7 @@ minetest.register_node(":air", {
groups = {not_in_creative_inventory=1}, groups = {not_in_creative_inventory=1},
}) })
minetest.register_node(":ignore", { core.register_node(":ignore", {
description = "Ignore (you hacker you!)", description = "Ignore (you hacker you!)",
inventory_image = "unknown_node.png", inventory_image = "unknown_node.png",
wield_image = "unknown_node.png", wield_image = "unknown_node.png",
@ -309,20 +309,20 @@ minetest.register_node(":ignore", {
}) })
-- The hand (bare definition) -- The hand (bare definition)
minetest.register_item(":", { core.register_item(":", {
type = "none", type = "none",
groups = {not_in_creative_inventory=1}, groups = {not_in_creative_inventory=1},
}) })
function minetest.override_item(name, redefinition) function core.override_item(name, redefinition)
if redefinition.name ~= nil then if redefinition.name ~= nil then
error("Attempt to redefine name of "..name.." to "..dump(redefinition.name), 2) error("Attempt to redefine name of "..name.." to "..dump(redefinition.name), 2)
end end
if redefinition.type ~= nil then if redefinition.type ~= nil then
error("Attempt to redefine type of "..name.." to "..dump(redefinition.type), 2) error("Attempt to redefine type of "..name.." to "..dump(redefinition.type), 2)
end end
local item = minetest.registered_items[name] local item = core.registered_items[name]
if not item then if not item then
error("Attempt to override non-existent item "..name, 2) error("Attempt to override non-existent item "..name, 2)
end end
@ -333,7 +333,7 @@ function minetest.override_item(name, redefinition)
end end
function minetest.run_callbacks(callbacks, mode, ...) function core.run_callbacks(callbacks, mode, ...)
assert(type(callbacks) == "table") assert(type(callbacks) == "table")
local cb_len = #callbacks local cb_len = #callbacks
if cb_len == 0 then if cb_len == 0 then
@ -387,24 +387,24 @@ local function make_registration_reverse()
return t, registerfunc return t, registerfunc
end end
minetest.registered_on_chat_messages, minetest.register_on_chat_message = make_registration() core.registered_on_chat_messages, core.register_on_chat_message = make_registration()
minetest.registered_globalsteps, minetest.register_globalstep = make_registration() core.registered_globalsteps, core.register_globalstep = make_registration()
minetest.registered_playerevents, minetest.register_playerevent = make_registration() core.registered_playerevents, core.register_playerevent = make_registration()
minetest.registered_on_mapgen_inits, minetest.register_on_mapgen_init = make_registration() core.registered_on_mapgen_inits, core.register_on_mapgen_init = make_registration()
minetest.registered_on_shutdown, minetest.register_on_shutdown = make_registration() core.registered_on_shutdown, core.register_on_shutdown = make_registration()
minetest.registered_on_punchnodes, minetest.register_on_punchnode = make_registration() core.registered_on_punchnodes, core.register_on_punchnode = make_registration()
minetest.registered_on_placenodes, minetest.register_on_placenode = make_registration() core.registered_on_placenodes, core.register_on_placenode = make_registration()
minetest.registered_on_dignodes, minetest.register_on_dignode = make_registration() core.registered_on_dignodes, core.register_on_dignode = make_registration()
minetest.registered_on_generateds, minetest.register_on_generated = make_registration() core.registered_on_generateds, core.register_on_generated = make_registration()
minetest.registered_on_newplayers, minetest.register_on_newplayer = make_registration() core.registered_on_newplayers, core.register_on_newplayer = make_registration()
minetest.registered_on_dieplayers, minetest.register_on_dieplayer = make_registration() core.registered_on_dieplayers, core.register_on_dieplayer = make_registration()
minetest.registered_on_respawnplayers, minetest.register_on_respawnplayer = make_registration() core.registered_on_respawnplayers, core.register_on_respawnplayer = make_registration()
minetest.registered_on_prejoinplayers, minetest.register_on_prejoinplayer = make_registration() core.registered_on_prejoinplayers, core.register_on_prejoinplayer = make_registration()
minetest.registered_on_joinplayers, minetest.register_on_joinplayer = make_registration() core.registered_on_joinplayers, core.register_on_joinplayer = make_registration()
minetest.registered_on_leaveplayers, minetest.register_on_leaveplayer = make_registration() core.registered_on_leaveplayers, core.register_on_leaveplayer = make_registration()
minetest.registered_on_player_receive_fields, minetest.register_on_player_receive_fields = make_registration_reverse() core.registered_on_player_receive_fields, core.register_on_player_receive_fields = make_registration_reverse()
minetest.registered_on_cheats, minetest.register_on_cheat = make_registration() core.registered_on_cheats, core.register_on_cheat = make_registration()
minetest.registered_on_crafts, minetest.register_on_craft = make_registration() core.registered_on_crafts, core.register_on_craft = make_registration()
minetest.registered_craft_predicts, minetest.register_craft_predict = make_registration() core.registered_craft_predicts, core.register_craft_predict = make_registration()
minetest.registered_on_protection_violation, minetest.register_on_protection_violation = make_registration() core.registered_on_protection_violation, core.register_on_protection_violation = make_registration()

@ -118,7 +118,7 @@ local function player_event_handler(player,eventname)
return false return false
end end
function minetest.hud_replace_builtin(name, definition) function core.hud_replace_builtin(name, definition)
if definition == nil or if definition == nil or
type(definition) ~= "table" or type(definition) ~= "table" or
@ -130,7 +130,7 @@ function minetest.hud_replace_builtin(name, definition)
health_bar_definition = definition health_bar_definition = definition
for name,ids in pairs(hud_ids) do for name,ids in pairs(hud_ids) do
local player = minetest.get_player_by_name(name) local player = core.get_player_by_name(name)
if player and hud_ids[name].id_healthbar then if player and hud_ids[name].id_healthbar then
player:hud_remove(hud_ids[name].id_healthbar) player:hud_remove(hud_ids[name].id_healthbar)
initialize_builtin_statbars(player) initialize_builtin_statbars(player)
@ -143,7 +143,7 @@ function minetest.hud_replace_builtin(name, definition)
breath_bar_definition = definition breath_bar_definition = definition
for name,ids in pairs(hud_ids) do for name,ids in pairs(hud_ids) do
local player = minetest.get_player_by_name(name) local player = core.get_player_by_name(name)
if player and hud_ids[name].id_breathbar then if player and hud_ids[name].id_breathbar then
player:hud_remove(hud_ids[name].id_breathbar) player:hud_remove(hud_ids[name].id_breathbar)
initialize_builtin_statbars(player) initialize_builtin_statbars(player)
@ -155,6 +155,6 @@ function minetest.hud_replace_builtin(name, definition)
return false return false
end end
minetest.register_on_joinplayer(initialize_builtin_statbars) core.register_on_joinplayer(initialize_builtin_statbars)
minetest.register_on_leaveplayer(cleanup_builtin_statbars) core.register_on_leaveplayer(cleanup_builtin_statbars)
minetest.register_playerevent(player_event_handler) core.register_playerevent(player_event_handler)

@ -1,10 +1,10 @@
-- Minetest: builtin/static_spawn.lua -- Minetest: builtin/static_spawn.lua
local function warn_invalid_static_spawnpoint() local function warn_invalid_static_spawnpoint()
if minetest.setting_get("static_spawnpoint") and if core.setting_get("static_spawnpoint") and
not minetest.setting_get_pos("static_spawnpoint") then not core.setting_get_pos("static_spawnpoint") then
minetest.log('error', "The static_spawnpoint setting is invalid: \"".. core.log('error', "The static_spawnpoint setting is invalid: \""..
minetest.setting_get("static_spawnpoint").."\"") core.setting_get("static_spawnpoint").."\"")
end end
end end
@ -12,22 +12,22 @@ warn_invalid_static_spawnpoint()
local function put_player_in_spawn(obj) local function put_player_in_spawn(obj)
warn_invalid_static_spawnpoint() warn_invalid_static_spawnpoint()
local static_spawnpoint = minetest.setting_get_pos("static_spawnpoint") local static_spawnpoint = core.setting_get_pos("static_spawnpoint")
if not static_spawnpoint then if not static_spawnpoint then
return false return false
end end
minetest.log('action', "Moving "..obj:get_player_name().. core.log('action', "Moving "..obj:get_player_name()..
" to static spawnpoint at ".. " to static spawnpoint at "..
minetest.pos_to_string(static_spawnpoint)) core.pos_to_string(static_spawnpoint))
obj:setpos(static_spawnpoint) obj:setpos(static_spawnpoint)
return true return true
end end
minetest.register_on_newplayer(function(obj) core.register_on_newplayer(function(obj)
put_player_in_spawn(obj) put_player_in_spawn(obj)
end) end)
minetest.register_on_respawnplayer(function(obj) core.register_on_respawnplayer(function(obj)
return put_player_in_spawn(obj) return put_player_in_spawn(obj)
end) end)

@ -5,13 +5,11 @@
-- before loading and running any mods. -- before loading and running any mods.
-- --
local core = minetest or engine
minetest = core
-- Initialize some very basic things -- Initialize some very basic things
print = core.debug print = core.debug
math.randomseed(os.time()) math.randomseed(os.time())
os.setlocale("C", "numeric") os.setlocale("C", "numeric")
minetest = core
-- Load other files -- Load other files
local scriptdir = core.get_builtin_path()..DIR_DELIM local scriptdir = core.get_builtin_path()..DIR_DELIM

@ -1,6 +1,7 @@
local menupath = engine.get_mainmenu_path()..DIR_DELIM engine = core
local commonpath = engine.get_builtin_path()..DIR_DELIM.."common"..DIR_DELIM local menupath = core.get_mainmenu_path()..DIR_DELIM
local commonpath = core.get_builtin_path()..DIR_DELIM.."common"..DIR_DELIM
dofile(menupath.."filterlist.lua") dofile(menupath.."filterlist.lua")
dofile(menupath.."modmgr.lua") dofile(menupath.."modmgr.lua")
@ -217,7 +218,7 @@ function menu.asyncOnlineFavourites()
menu.favorites = {} menu.favorites = {}
engine.handle_async( engine.handle_async(
function(param) function(param)
return engine.get_favorites("online") --return core.get_favorites("online")
end, end,
nil, nil,
function(result) function(result)

@ -193,16 +193,9 @@ function modmgr.identify_modname(modpath,filename)
while line~= nil do while line~= nil do
local modname = nil local modname = nil
if line:find("minetest.register_tool") then if line:find("register_tool") or
modname = modmgr.parse_register_line(line) line:find("register_craftitem") or
end line:find("register_node") then
if line:find("minetest.register_craftitem") then
modname = modmgr.parse_register_line(line)
end
if line:find("minetest.register_node") then
modname = modmgr.parse_register_line(line) modname = modmgr.parse_register_line(line)
end end
@ -225,7 +218,6 @@ end
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
function modmgr.tab() function modmgr.tab()
if modmgr.global_mods == nil then if modmgr.global_mods == nil then
modmgr.refresh_globals() modmgr.refresh_globals()
end end

@ -3,7 +3,7 @@ Minetest Lua Mainmenu API Reference 0.4.9
Introduction Introduction
------------- -------------
The main menu is defined as a formspec by Lua in builtin/mainmenu.lua The main menu is defined as a formspec by Lua in builtin/mainmenu/
Description of formspec language to show your menu is in lua_api.txt Description of formspec language to show your menu is in lua_api.txt
Callbacks Callbacks
@ -83,7 +83,7 @@ engine.download_file(url,target) (possible in async calls)
^ target to store to ^ target to store to
^ returns true/false ^ returns true/false
engine.get_version() (possible in async calls) engine.get_version() (possible in async calls)
^ returns current minetest version ^ returns current core version
engine.sound_play(spec, looped) -> handle engine.sound_play(spec, looped) -> handle
^ spec = SimpleSoundSpec (see lua-api.txt) ^ spec = SimpleSoundSpec (see lua-api.txt)
^ looped = bool ^ looped = bool
@ -191,14 +191,14 @@ fgettext(string, ...) -> string
^ call engine.gettext(string), replace "$1"..."$9" with the given ^ call engine.gettext(string), replace "$1"..."$9" with the given
^ extra arguments, call engine.formspec_escape and return the result ^ extra arguments, call engine.formspec_escape and return the result
engine.parse_json(string[, nullvalue]) -> something (possible in async calls) engine.parse_json(string[, nullvalue]) -> something (possible in async calls)
^ see minetest.parse_json (lua_api.txt) ^ see core.parse_json (lua_api.txt)
dump(obj, dumped={}) dump(obj, dumped={})
^ Return object serialized as a string ^ Return object serialized as a string
string:split(separator) string:split(separator)
^ eg. string:split("a,b", ",") == {"a","b"} ^ eg. string:split("a,b", ",") == {"a","b"}
string:trim() string:trim()
^ eg. string.trim("\n \t\tfoo bar\t ") == "foo bar" ^ eg. string.trim("\n \t\tfoo bar\t ") == "foo bar"
minetest.is_yes(arg) (possible in async calls) core.is_yes(arg) (possible in async calls)
^ returns whether arg can be interpreted as yes ^ returns whether arg can be interpreted as yes
Async: Async:

@ -955,14 +955,14 @@ std::vector<ItemStack> read_items(lua_State *L, int index, Server *srv)
/******************************************************************************/ /******************************************************************************/
void luaentity_get(lua_State *L, u16 id) void luaentity_get(lua_State *L, u16 id)
{ {
// Get minetest.luaentities[i] // Get luaentities[i]
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "luaentities"); lua_getfield(L, -1, "luaentities");
luaL_checktype(L, -1, LUA_TTABLE); luaL_checktype(L, -1, LUA_TTABLE);
lua_pushnumber(L, id); lua_pushnumber(L, id);
lua_gettable(L, -2); lua_gettable(L, -2);
lua_remove(L, -2); // luaentities lua_remove(L, -2); // Remove luaentities
lua_remove(L, -2); // minetest lua_remove(L, -2); // Remove core
} }
/******************************************************************************/ /******************************************************************************/

@ -92,8 +92,8 @@ void script_run_callbacks(lua_State *L, int nargs, RunCallbacksMode mode)
int errorhandler = lua_gettop(L) - nargs - 1; int errorhandler = lua_gettop(L) - nargs - 1;
lua_insert(L, errorhandler); lua_insert(L, errorhandler);
// Insert minetest.run_callbacks between error handler and table // Insert run_callbacks between error handler and table
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "run_callbacks"); lua_getfield(L, -1, "run_callbacks");
lua_remove(L, -2); lua_remove(L, -2);
lua_insert(L, errorhandler + 1); lua_insert(L, errorhandler + 1);

@ -146,7 +146,7 @@ void AsyncEngine::putJobResult(LuaJobInfo result)
/******************************************************************************/ /******************************************************************************/
void AsyncEngine::step(lua_State *L, int errorhandler) void AsyncEngine::step(lua_State *L, int errorhandler)
{ {
lua_getglobal(L, "engine"); lua_getglobal(L, "core");
resultQueueMutex.Lock(); resultQueueMutex.Lock();
while (!resultQueue.empty()) { while (!resultQueue.empty()) {
LuaJobInfo jobDone = resultQueue.front(); LuaJobInfo jobDone = resultQueue.front();
@ -169,7 +169,7 @@ void AsyncEngine::step(lua_State *L, int errorhandler)
} }
} }
resultQueueMutex.Unlock(); resultQueueMutex.Unlock();
lua_pop(L, 1); // Pop engine lua_pop(L, 1); // Pop core
} }
/******************************************************************************/ /******************************************************************************/
@ -223,17 +223,10 @@ AsyncWorkerThread::AsyncWorkerThread(AsyncEngine* jobDispatcher,
{ {
lua_State *L = getStack(); lua_State *L = getStack();
luaL_openlibs(L);
// Prepare job lua environment // Prepare job lua environment
lua_newtable(L); lua_getglobal(L, "core");
lua_setglobal(L, "engine");
lua_getglobal(L, "engine");
int top = lua_gettop(L); int top = lua_gettop(L);
lua_pushstring(L, DIR_DELIM);
lua_setglobal(L, "DIR_DELIM");
// Push builtin initialization type // Push builtin initialization type
lua_pushstring(L, "async"); lua_pushstring(L, "async");
lua_setglobal(L, "INIT"); lua_setglobal(L, "INIT");
@ -278,9 +271,9 @@ void* AsyncWorkerThread::Thread()
continue; continue;
} }
lua_getglobal(L, "engine"); lua_getglobal(L, "core");
if (lua_isnil(L, -1)) { if (lua_isnil(L, -1)) {
errorstream << "Unable to find engine within async environment!"; errorstream << "Unable to find core within async environment!";
abort(); abort();
} }
@ -310,7 +303,7 @@ void* AsyncWorkerThread::Thread()
toProcess.serializedResult = std::string(retval, length); toProcess.serializedResult = std::string(retval, length);
} }
// Pop engine, job_processor, and retval // Pop core, job_processor, and retval
lua_pop(L, 3); lua_pop(L, 3);
// Put job result // Put job result

@ -22,6 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "lua_api/l_object.h" #include "lua_api/l_object.h"
#include "serverobject.h" #include "serverobject.h"
#include "debug.h" #include "debug.h"
#include "filesys.h"
#include "log.h" #include "log.h"
#include "mods.h" #include "mods.h"
#include "util/string.h" #include "util/string.h"
@ -48,13 +49,13 @@ public:
{ {
// Store current modname in registry // Store current modname in registry
lua_pushstring(L, modname.c_str()); lua_pushstring(L, modname.c_str());
lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname"); lua_setfield(L, LUA_REGISTRYINDEX, "current_modname");
} }
~ModNameStorer() ~ModNameStorer()
{ {
// Clear current modname in registry // Clear current modname in registry
lua_pushnil(L); lua_pushnil(L);
lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname"); lua_setfield(L, LUA_REGISTRYINDEX, "current_modname");
} }
}; };
@ -72,6 +73,8 @@ ScriptApiBase::ScriptApiBase()
m_luastack = luaL_newstate(); m_luastack = luaL_newstate();
assert(m_luastack); assert(m_luastack);
luaL_openlibs(m_luastack);
// Add and save an error handler // Add and save an error handler
lua_pushcfunction(m_luastack, script_error_handler); lua_pushcfunction(m_luastack, script_error_handler);
m_errorhandler = lua_gettop(m_luastack); m_errorhandler = lua_gettop(m_luastack);
@ -88,6 +91,13 @@ ScriptApiBase::ScriptApiBase()
lua_pop(m_luastack, 1); lua_pop(m_luastack, 1);
#endif #endif
// Add basic globals
lua_newtable(m_luastack);
lua_setglobal(m_luastack, "core");
lua_pushstring(m_luastack, DIR_DELIM);
lua_setglobal(m_luastack, "DIR_DELIM");
m_server = NULL; m_server = NULL;
m_environment = NULL; m_environment = NULL;
m_guiengine = NULL; m_guiengine = NULL;
@ -191,8 +201,8 @@ void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
int object = lua_gettop(L); int object = lua_gettop(L);
// Get minetest.object_refs table // Get core.object_refs table
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "object_refs"); lua_getfield(L, -1, "object_refs");
luaL_checktype(L, -1, LUA_TTABLE); luaL_checktype(L, -1, LUA_TTABLE);
int objectstable = lua_gettop(L); int objectstable = lua_gettop(L);
@ -208,8 +218,8 @@ void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
//infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl; //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
// Get minetest.object_refs table // Get core.object_refs table
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "object_refs"); lua_getfield(L, -1, "object_refs");
luaL_checktype(L, -1, LUA_TTABLE); luaL_checktype(L, -1, LUA_TTABLE);
int objectstable = lua_gettop(L); int objectstable = lua_gettop(L);
@ -244,12 +254,12 @@ void ScriptApiBase::objectrefGet(u16 id)
{ {
lua_State *L = getStack(); lua_State *L = getStack();
// Get minetest.object_refs[i] // Get core.object_refs[i]
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "object_refs"); lua_getfield(L, -1, "object_refs");
luaL_checktype(L, -1, LUA_TTABLE); luaL_checktype(L, -1, LUA_TTABLE);
lua_pushnumber(L, id); lua_pushnumber(L, id);
lua_gettable(L, -2); lua_gettable(L, -2);
lua_remove(L, -2); // object_refs lua_remove(L, -2); // object_refs
lua_remove(L, -2); // minetest lua_remove(L, -2); // core
} }

@ -31,8 +31,8 @@ bool ScriptApiEntity::luaentity_Add(u16 id, const char *name)
verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\"" verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
<<name<<"\""<<std::endl; <<name<<"\""<<std::endl;
// Get minetest.registered_entities[name] // Get core.registered_entities[name]
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_entities"); lua_getfield(L, -1, "registered_entities");
luaL_checktype(L, -1, LUA_TTABLE); luaL_checktype(L, -1, LUA_TTABLE);
lua_pushstring(L, name); lua_pushstring(L, name);
@ -62,8 +62,8 @@ bool ScriptApiEntity::luaentity_Add(u16 id, const char *name)
luaL_typerror(L, -1, "ObjectRef"); luaL_typerror(L, -1, "ObjectRef");
lua_setfield(L, -2, "object"); lua_setfield(L, -2, "object");
// minetest.luaentities[id] = object // core.luaentities[id] = object
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "luaentities"); lua_getfield(L, -1, "luaentities");
luaL_checktype(L, -1, LUA_TTABLE); luaL_checktype(L, -1, LUA_TTABLE);
lua_pushnumber(L, id); // Push id lua_pushnumber(L, id); // Push id
@ -80,7 +80,7 @@ void ScriptApiEntity::luaentity_Activate(u16 id,
verbosestream << "scriptapi_luaentity_activate: id=" << id << std::endl; verbosestream << "scriptapi_luaentity_activate: id=" << id << std::endl;
// Get minetest.luaentities[id] // Get core.luaentities[id]
luaentity_get(L, id); luaentity_get(L, id);
int object = lua_gettop(L); int object = lua_gettop(L);
@ -106,8 +106,8 @@ void ScriptApiEntity::luaentity_Remove(u16 id)
verbosestream << "scriptapi_luaentity_rm: id=" << id << std::endl; verbosestream << "scriptapi_luaentity_rm: id=" << id << std::endl;
// Get minetest.luaentities table // Get core.luaentities table
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "luaentities"); lua_getfield(L, -1, "luaentities");
luaL_checktype(L, -1, LUA_TTABLE); luaL_checktype(L, -1, LUA_TTABLE);
int objectstable = lua_gettop(L); int objectstable = lua_gettop(L);
@ -117,7 +117,7 @@ void ScriptApiEntity::luaentity_Remove(u16 id)
lua_pushnil(L); lua_pushnil(L);
lua_settable(L, objectstable); lua_settable(L, objectstable);
lua_pop(L, 2); // pop luaentities, minetest lua_pop(L, 2); // pop luaentities, core
} }
std::string ScriptApiEntity::luaentity_GetStaticdata(u16 id) std::string ScriptApiEntity::luaentity_GetStaticdata(u16 id)
@ -126,7 +126,7 @@ std::string ScriptApiEntity::luaentity_GetStaticdata(u16 id)
//infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl; //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
// Get minetest.luaentities[id] // Get core.luaentities[id]
luaentity_get(L, id); luaentity_get(L, id);
int object = lua_gettop(L); int object = lua_gettop(L);
@ -157,7 +157,7 @@ void ScriptApiEntity::luaentity_GetProperties(u16 id,
//infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl; //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
// Get minetest.luaentities[id] // Get core.luaentities[id]
luaentity_get(L, id); luaentity_get(L, id);
// Set default values that differ from ObjectProperties defaults // Set default values that differ from ObjectProperties defaults
@ -196,7 +196,7 @@ void ScriptApiEntity::luaentity_Step(u16 id, float dtime)
//infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl; //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
// Get minetest.luaentities[id] // Get core.luaentities[id]
luaentity_get(L, id); luaentity_get(L, id);
int object = lua_gettop(L); int object = lua_gettop(L);
// State: object is at top of stack // State: object is at top of stack
@ -225,7 +225,7 @@ void ScriptApiEntity::luaentity_Punch(u16 id,
//infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl; //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
// Get minetest.luaentities[id] // Get core.luaentities[id]
luaentity_get(L,id); luaentity_get(L,id);
int object = lua_gettop(L); int object = lua_gettop(L);
// State: object is at top of stack // State: object is at top of stack
@ -255,7 +255,7 @@ void ScriptApiEntity::luaentity_Rightclick(u16 id,
//infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl; //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
// Get minetest.luaentities[id] // Get core.luaentities[id]
luaentity_get(L, id); luaentity_get(L, id);
int object = lua_gettop(L); int object = lua_gettop(L);
// State: object is at top of stack // State: object is at top of stack

@ -31,8 +31,8 @@ void ScriptApiEnv::environment_OnGenerated(v3s16 minp, v3s16 maxp,
{ {
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
// Get minetest.registered_on_generateds // Get core.registered_on_generateds
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_generateds"); lua_getfield(L, -1, "registered_on_generateds");
// Call callbacks // Call callbacks
push_v3s16(L, minp); push_v3s16(L, minp);
@ -46,8 +46,8 @@ void ScriptApiEnv::environment_Step(float dtime)
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
//infostream<<"scriptapi_environment_step"<<std::endl; //infostream<<"scriptapi_environment_step"<<std::endl;
// Get minetest.registered_globalsteps // Get core.registered_globalsteps
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_globalsteps"); lua_getfield(L, -1, "registered_globalsteps");
// Call callbacks // Call callbacks
lua_pushnumber(L, dtime); lua_pushnumber(L, dtime);
@ -80,8 +80,8 @@ void ScriptApiEnv::environment_OnMapgenInit(MapgenParams *mgparams)
{ {
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
// Get minetest.registered_on_mapgen_inits // Get core.registered_on_mapgen_inits
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_mapgen_inits"); lua_getfield(L, -1, "registered_on_mapgen_inits");
// Call callbacks // Call callbacks
@ -114,8 +114,8 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env)
Add ActiveBlockModifiers to environment Add ActiveBlockModifiers to environment
*/ */
// Get minetest.registered_abms // Get core.registered_abms
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_abms"); lua_getfield(L, -1, "registered_abms");
luaL_checktype(L, -1, LUA_TTABLE); luaL_checktype(L, -1, LUA_TTABLE);
int registered_abms = lua_gettop(L); int registered_abms = lua_gettop(L);

@ -193,7 +193,7 @@ void ScriptApiDetached::detached_inventory_OnTake(
scriptError(); scriptError();
} }
// Retrieves minetest.detached_inventories[name][callbackname] // Retrieves core.detached_inventories[name][callbackname]
// If that is nil or on error, return false and stack is unchanged // If that is nil or on error, return false and stack is unchanged
// If that is a function, returns true and pushes the // If that is a function, returns true and pushes the
// function onto the stack // function onto the stack
@ -202,7 +202,7 @@ bool ScriptApiDetached::getDetachedInventoryCallback(
{ {
lua_State *L = getStack(); lua_State *L = getStack();
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "detached_inventories"); lua_getfield(L, -1, "detached_inventories");
lua_remove(L, -2); lua_remove(L, -2);
luaL_checktype(L, -1, LUA_TTABLE); luaL_checktype(L, -1, LUA_TTABLE);

@ -112,7 +112,7 @@ bool ScriptApiItem::item_OnCraft(ItemStack &item, ServerActiveObject *user,
{ {
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "on_craft"); lua_getfield(L, -1, "on_craft");
LuaItemStack::create(L, item); LuaItemStack::create(L, item);
objectrefGetOrCreate(user); objectrefGetOrCreate(user);
@ -143,7 +143,7 @@ bool ScriptApiItem::item_CraftPredict(ItemStack &item, ServerActiveObject *user,
{ {
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "craft_predict"); lua_getfield(L, -1, "craft_predict");
LuaItemStack::create(L, item); LuaItemStack::create(L, item);
objectrefGetOrCreate(user); objectrefGetOrCreate(user);
@ -169,19 +169,19 @@ bool ScriptApiItem::item_CraftPredict(ItemStack &item, ServerActiveObject *user,
return true; return true;
} }
// Retrieves minetest.registered_items[name][callbackname] // Retrieves core.registered_items[name][callbackname]
// If that is nil or on error, return false and stack is unchanged // If that is nil or on error, return false and stack is unchanged
// If that is a function, returns true and pushes the // If that is a function, returns true and pushes the
// function onto the stack // function onto the stack
// If minetest.registered_items[name] doesn't exist, minetest.nodedef_default // If core.registered_items[name] doesn't exist, core.nodedef_default
// is tried instead so unknown items can still be manipulated to some degree // is tried instead so unknown items can still be manipulated to some degree
bool ScriptApiItem::getItemCallback(const char *name, const char *callbackname) bool ScriptApiItem::getItemCallback(const char *name, const char *callbackname)
{ {
lua_State* L = getStack(); lua_State* L = getStack();
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_items"); lua_getfield(L, -1, "registered_items");
lua_remove(L, -2); // Remove minetest lua_remove(L, -2); // Remove core
luaL_checktype(L, -1, LUA_TTABLE); luaL_checktype(L, -1, LUA_TTABLE);
lua_getfield(L, -1, name); lua_getfield(L, -1, name);
lua_remove(L, -2); // Remove registered_items lua_remove(L, -2); // Remove registered_items
@ -192,8 +192,8 @@ bool ScriptApiItem::getItemCallback(const char *name, const char *callbackname)
errorstream << "Item \"" << name << "\" not defined" << std::endl; errorstream << "Item \"" << name << "\" not defined" << std::endl;
lua_pop(L, 1); lua_pop(L, 1);
// Try minetest.nodedef_default instead // Try core.nodedef_default instead
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "nodedef_default"); lua_getfield(L, -1, "nodedef_default");
lua_remove(L, -2); lua_remove(L, -2);
luaL_checktype(L, -1, LUA_TTABLE); luaL_checktype(L, -1, LUA_TTABLE);

@ -38,9 +38,9 @@ void ScriptApiMainMenu::handleMainMenuEvent(std::string text)
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
// Get handler function // Get handler function
lua_getglobal(L, "engine"); lua_getglobal(L, "core");
lua_getfield(L, -1, "event_handler"); lua_getfield(L, -1, "event_handler");
lua_remove(L, -2); // Remove engine lua_remove(L, -2); // Remove core
if (lua_isnil(L, -1)) { if (lua_isnil(L, -1)) {
lua_pop(L, 1); // Pop event_handler lua_pop(L, 1); // Pop event_handler
return; return;
@ -58,9 +58,9 @@ void ScriptApiMainMenu::handleMainMenuButtons(std::map<std::string, std::string>
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
// Get handler function // Get handler function
lua_getglobal(L, "engine"); lua_getglobal(L, "core");
lua_getfield(L, -1, "button_handler"); lua_getfield(L, -1, "button_handler");
lua_remove(L, -2); // Remove engine lua_remove(L, -2); // Remove core
if (lua_isnil(L, -1)) { if (lua_isnil(L, -1)) {
lua_pop(L, 1); // Pop button handler lua_pop(L, 1); // Pop button handler
return; return;

@ -25,8 +25,8 @@ void ScriptApiPlayer::on_newplayer(ServerActiveObject *player)
{ {
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
// Get minetest.registered_on_newplayers // Get core.registered_on_newplayers
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_newplayers"); lua_getfield(L, -1, "registered_on_newplayers");
// Call callbacks // Call callbacks
objectrefGetOrCreate(player); objectrefGetOrCreate(player);
@ -37,8 +37,8 @@ void ScriptApiPlayer::on_dieplayer(ServerActiveObject *player)
{ {
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
// Get minetest.registered_on_dieplayers // Get core.registered_on_dieplayers
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_dieplayers"); lua_getfield(L, -1, "registered_on_dieplayers");
// Call callbacks // Call callbacks
objectrefGetOrCreate(player); objectrefGetOrCreate(player);
@ -49,8 +49,8 @@ bool ScriptApiPlayer::on_respawnplayer(ServerActiveObject *player)
{ {
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
// Get minetest.registered_on_respawnplayers // Get core.registered_on_respawnplayers
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_respawnplayers"); lua_getfield(L, -1, "registered_on_respawnplayers");
// Call callbacks // Call callbacks
objectrefGetOrCreate(player); objectrefGetOrCreate(player);
@ -63,8 +63,8 @@ bool ScriptApiPlayer::on_prejoinplayer(std::string name, std::string ip, std::st
{ {
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
// Get minetest.registered_on_prejoinplayers // Get core.registered_on_prejoinplayers
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_prejoinplayers"); lua_getfield(L, -1, "registered_on_prejoinplayers");
lua_pushstring(L, name.c_str()); lua_pushstring(L, name.c_str());
lua_pushstring(L, ip.c_str()); lua_pushstring(L, ip.c_str());
@ -80,8 +80,8 @@ void ScriptApiPlayer::on_joinplayer(ServerActiveObject *player)
{ {
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
// Get minetest.registered_on_joinplayers // Get core.registered_on_joinplayers
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_joinplayers"); lua_getfield(L, -1, "registered_on_joinplayers");
// Call callbacks // Call callbacks
objectrefGetOrCreate(player); objectrefGetOrCreate(player);
@ -92,8 +92,8 @@ void ScriptApiPlayer::on_leaveplayer(ServerActiveObject *player)
{ {
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
// Get minetest.registered_on_leaveplayers // Get core.registered_on_leaveplayers
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_leaveplayers"); lua_getfield(L, -1, "registered_on_leaveplayers");
// Call callbacks // Call callbacks
objectrefGetOrCreate(player); objectrefGetOrCreate(player);
@ -105,8 +105,8 @@ void ScriptApiPlayer::on_cheat(ServerActiveObject *player,
{ {
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
// Get minetest.registered_on_cheats // Get core.registered_on_cheats
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_cheats"); lua_getfield(L, -1, "registered_on_cheats");
// Call callbacks // Call callbacks
objectrefGetOrCreate(player); objectrefGetOrCreate(player);
@ -122,8 +122,8 @@ void ScriptApiPlayer::on_playerReceiveFields(ServerActiveObject *player,
{ {
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
// Get minetest.registered_on_chat_messages // Get core.registered_on_chat_messages
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_player_receive_fields"); lua_getfield(L, -1, "registered_on_player_receive_fields");
// Call callbacks // Call callbacks
// param 1 // param 1

@ -62,13 +62,13 @@ void ScriptApiServer::getAuthHandler()
{ {
lua_State *L = getStack(); lua_State *L = getStack();
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_auth_handler"); lua_getfield(L, -1, "registered_auth_handler");
if (lua_isnil(L, -1)){ if (lua_isnil(L, -1)){
lua_pop(L, 1); lua_pop(L, 1);
lua_getfield(L, -1, "builtin_auth_handler"); lua_getfield(L, -1, "builtin_auth_handler");
} }
lua_remove(L, -2); // Remove minetest lua_remove(L, -2); // Remove core
if (lua_type(L, -1) != LUA_TTABLE) if (lua_type(L, -1) != LUA_TTABLE)
throw LuaError("Authentication handler table not valid"); throw LuaError("Authentication handler table not valid");
} }
@ -130,8 +130,8 @@ bool ScriptApiServer::on_chat_message(const std::string &name,
{ {
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
// Get minetest.registered_on_chat_messages // Get core.registered_on_chat_messages
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_chat_messages"); lua_getfield(L, -1, "registered_on_chat_messages");
// Call callbacks // Call callbacks
lua_pushstring(L, name.c_str()); lua_pushstring(L, name.c_str());
@ -146,7 +146,7 @@ void ScriptApiServer::on_shutdown()
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
// Get registered shutdown hooks // Get registered shutdown hooks
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_shutdown"); lua_getfield(L, -1, "registered_on_shutdown");
// Call callbacks // Call callbacks
script_run_callbacks(L, 0, RUN_CALLBACKS_MODE_FIRST); script_run_callbacks(L, 0, RUN_CALLBACKS_MODE_FIRST);

@ -56,24 +56,24 @@ void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n,
lua_pushcfunction(L, script_error_handler); lua_pushcfunction(L, script_error_handler);
int errorhandler = lua_gettop(L); int errorhandler = lua_gettop(L);
// Get minetest.registered_abms // Get registered_abms
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_abms"); lua_getfield(L, -1, "registered_abms");
luaL_checktype(L, -1, LUA_TTABLE); luaL_checktype(L, -1, LUA_TTABLE);
lua_remove(L, -2); // Remove "minetest" lua_remove(L, -2); // Remove core
// Get minetest.registered_abms[m_id] // Get registered_abms[m_id]
lua_pushnumber(L, m_id); lua_pushnumber(L, m_id);
lua_gettable(L, -2); lua_gettable(L, -2);
if(lua_isnil(L, -1)) if(lua_isnil(L, -1))
assert(0); assert(0);
lua_remove(L, -2); // Remove "registered_abms" lua_remove(L, -2); // Remove registered_abms
// Call action // Call action
luaL_checktype(L, -1, LUA_TTABLE); luaL_checktype(L, -1, LUA_TTABLE);
lua_getfield(L, -1, "action"); lua_getfield(L, -1, "action");
luaL_checktype(L, -1, LUA_TFUNCTION); luaL_checktype(L, -1, LUA_TFUNCTION);
lua_remove(L, -2); // Remove "registered_abms[m_id]" lua_remove(L, -2); // Remove registered_abms[m_id]
push_v3s16(L, p); push_v3s16(L, p);
pushnode(L, n, env->getGameDef()->ndef()); pushnode(L, n, env->getGameDef()->ndef());
lua_pushnumber(L, active_object_count); lua_pushnumber(L, active_object_count);
@ -85,7 +85,7 @@ void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n,
// Exported functions // Exported functions
// minetest.set_node(pos, node) // set_node(pos, node)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
int ModApiEnvMod::l_set_node(lua_State *L) int ModApiEnvMod::l_set_node(lua_State *L)
{ {
@ -106,7 +106,7 @@ int ModApiEnvMod::l_add_node(lua_State *L)
return l_set_node(L); return l_set_node(L);
} }
// minetest.remove_node(pos) // remove_node(pos)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
int ModApiEnvMod::l_remove_node(lua_State *L) int ModApiEnvMod::l_remove_node(lua_State *L)
{ {
@ -120,7 +120,7 @@ int ModApiEnvMod::l_remove_node(lua_State *L)
return 1; return 1;
} }
// minetest.swap_node(pos, node) // swap_node(pos, node)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
int ModApiEnvMod::l_swap_node(lua_State *L) int ModApiEnvMod::l_swap_node(lua_State *L)
{ {
@ -136,7 +136,7 @@ int ModApiEnvMod::l_swap_node(lua_State *L)
return 1; return 1;
} }
// minetest.get_node(pos) // get_node(pos)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
int ModApiEnvMod::l_get_node(lua_State *L) int ModApiEnvMod::l_get_node(lua_State *L)
{ {
@ -151,7 +151,7 @@ int ModApiEnvMod::l_get_node(lua_State *L)
return 1; return 1;
} }
// minetest.get_node_or_nil(pos) // get_node_or_nil(pos)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
int ModApiEnvMod::l_get_node_or_nil(lua_State *L) int ModApiEnvMod::l_get_node_or_nil(lua_State *L)
{ {
@ -172,7 +172,7 @@ int ModApiEnvMod::l_get_node_or_nil(lua_State *L)
} }
} }
// minetest.get_node_light(pos, timeofday) // get_node_light(pos, timeofday)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
// timeofday: nil = current time, 0 = night, 0.5 = day // timeofday: nil = current time, 0 = night, 0.5 = day
int ModApiEnvMod::l_get_node_light(lua_State *L) int ModApiEnvMod::l_get_node_light(lua_State *L)
@ -198,7 +198,7 @@ int ModApiEnvMod::l_get_node_light(lua_State *L)
} }
} }
// minetest.place_node(pos, node) // place_node(pos, node)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
int ModApiEnvMod::l_place_node(lua_State *L) int ModApiEnvMod::l_place_node(lua_State *L)
{ {
@ -232,7 +232,7 @@ int ModApiEnvMod::l_place_node(lua_State *L)
return 1; return 1;
} }
// minetest.dig_node(pos) // dig_node(pos)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
int ModApiEnvMod::l_dig_node(lua_State *L) int ModApiEnvMod::l_dig_node(lua_State *L)
{ {
@ -255,7 +255,7 @@ int ModApiEnvMod::l_dig_node(lua_State *L)
return 1; return 1;
} }
// minetest.punch_node(pos) // punch_node(pos)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
int ModApiEnvMod::l_punch_node(lua_State *L) int ModApiEnvMod::l_punch_node(lua_State *L)
{ {
@ -278,7 +278,7 @@ int ModApiEnvMod::l_punch_node(lua_State *L)
return 1; return 1;
} }
// minetest.get_node_max_level(pos) // get_node_max_level(pos)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
int ModApiEnvMod::l_get_node_max_level(lua_State *L) int ModApiEnvMod::l_get_node_max_level(lua_State *L)
{ {
@ -290,7 +290,7 @@ int ModApiEnvMod::l_get_node_max_level(lua_State *L)
return 1; return 1;
} }
// minetest.get_node_level(pos) // get_node_level(pos)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
int ModApiEnvMod::l_get_node_level(lua_State *L) int ModApiEnvMod::l_get_node_level(lua_State *L)
{ {
@ -302,7 +302,7 @@ int ModApiEnvMod::l_get_node_level(lua_State *L)
return 1; return 1;
} }
// minetest.set_node_level(pos, level) // set_node_level(pos, level)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
// level: 0..63 // level: 0..63
int ModApiEnvMod::l_set_node_level(lua_State *L) int ModApiEnvMod::l_set_node_level(lua_State *L)
@ -319,7 +319,7 @@ int ModApiEnvMod::l_set_node_level(lua_State *L)
return 1; return 1;
} }
// minetest.add_node_level(pos, level) // add_node_level(pos, level)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
// level: 0..63 // level: 0..63
int ModApiEnvMod::l_add_node_level(lua_State *L) int ModApiEnvMod::l_add_node_level(lua_State *L)
@ -337,7 +337,7 @@ int ModApiEnvMod::l_add_node_level(lua_State *L)
} }
// minetest.get_meta(pos) // get_meta(pos)
int ModApiEnvMod::l_get_meta(lua_State *L) int ModApiEnvMod::l_get_meta(lua_State *L)
{ {
GET_ENV_PTR; GET_ENV_PTR;
@ -348,7 +348,7 @@ int ModApiEnvMod::l_get_meta(lua_State *L)
return 1; return 1;
} }
// minetest.get_node_timer(pos) // get_node_timer(pos)
int ModApiEnvMod::l_get_node_timer(lua_State *L) int ModApiEnvMod::l_get_node_timer(lua_State *L)
{ {
GET_ENV_PTR; GET_ENV_PTR;
@ -359,7 +359,7 @@ int ModApiEnvMod::l_get_node_timer(lua_State *L)
return 1; return 1;
} }
// minetest.add_entity(pos, entityname) -> ObjectRef or nil // add_entity(pos, entityname) -> ObjectRef or nil
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
int ModApiEnvMod::l_add_entity(lua_State *L) int ModApiEnvMod::l_add_entity(lua_State *L)
{ {
@ -380,7 +380,7 @@ int ModApiEnvMod::l_add_entity(lua_State *L)
return 1; return 1;
} }
// minetest.add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
int ModApiEnvMod::l_add_item(lua_State *L) int ModApiEnvMod::l_add_item(lua_State *L)
{ {
@ -396,10 +396,10 @@ int ModApiEnvMod::l_add_item(lua_State *L)
lua_pushcfunction(L, script_error_handler); lua_pushcfunction(L, script_error_handler);
int errorhandler = lua_gettop(L); int errorhandler = lua_gettop(L);
// Use minetest.spawn_item to spawn a __builtin:item // Use spawn_item to spawn a __builtin:item
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "spawn_item"); lua_getfield(L, -1, "spawn_item");
lua_remove(L, -2); // Remove minetest lua_remove(L, -2); // Remove core
if(lua_isnil(L, -1)) if(lua_isnil(L, -1))
return 0; return 0;
lua_pushvalue(L, 1); lua_pushvalue(L, 1);
@ -423,7 +423,7 @@ int ModApiEnvMod::l_add_item(lua_State *L)
return 1;*/ return 1;*/
} }
// minetest.get_player_by_name(name) // get_player_by_name(name)
int ModApiEnvMod::l_get_player_by_name(lua_State *L) int ModApiEnvMod::l_get_player_by_name(lua_State *L)
{ {
GET_ENV_PTR; GET_ENV_PTR;
@ -445,7 +445,7 @@ int ModApiEnvMod::l_get_player_by_name(lua_State *L)
return 1; return 1;
} }
// minetest.get_objects_inside_radius(pos, radius) // get_objects_inside_radius(pos, radius)
int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L) int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
{ {
GET_ENV_PTR; GET_ENV_PTR;
@ -466,7 +466,7 @@ int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
return 1; return 1;
} }
// minetest.set_timeofday(val) // set_timeofday(val)
// val = 0...1 // val = 0...1
int ModApiEnvMod::l_set_timeofday(lua_State *L) int ModApiEnvMod::l_set_timeofday(lua_State *L)
{ {
@ -484,7 +484,7 @@ int ModApiEnvMod::l_set_timeofday(lua_State *L)
return 0; return 0;
} }
// minetest.get_timeofday() -> 0...1 // get_timeofday() -> 0...1
int ModApiEnvMod::l_get_timeofday(lua_State *L) int ModApiEnvMod::l_get_timeofday(lua_State *L)
{ {
GET_ENV_PTR; GET_ENV_PTR;
@ -496,7 +496,7 @@ int ModApiEnvMod::l_get_timeofday(lua_State *L)
return 1; return 1;
} }
// minetest.get_gametime() // get_gametime()
int ModApiEnvMod::l_get_gametime(lua_State *L) int ModApiEnvMod::l_get_gametime(lua_State *L)
{ {
GET_ENV_PTR; GET_ENV_PTR;
@ -507,7 +507,7 @@ int ModApiEnvMod::l_get_gametime(lua_State *L)
} }
// minetest.find_node_near(pos, radius, nodenames) -> pos or nil // find_node_near(pos, radius, nodenames) -> pos or nil
// nodenames: eg. {"ignore", "group:tree"} or "default:dirt" // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
int ModApiEnvMod::l_find_node_near(lua_State *L) int ModApiEnvMod::l_find_node_near(lua_State *L)
{ {
@ -547,7 +547,7 @@ int ModApiEnvMod::l_find_node_near(lua_State *L)
return 0; return 0;
} }
// minetest.find_nodes_in_area(minp, maxp, nodenames) -> list of positions // find_nodes_in_area(minp, maxp, nodenames) -> list of positions
// nodenames: eg. {"ignore", "group:tree"} or "default:dirt" // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
int ModApiEnvMod::l_find_nodes_in_area(lua_State *L) int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
{ {
@ -586,7 +586,7 @@ int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
return 1; return 1;
} }
// minetest.get_perlin(seeddiff, octaves, persistence, scale) // get_perlin(seeddiff, octaves, persistence, scale)
// returns world-specific PerlinNoise // returns world-specific PerlinNoise
int ModApiEnvMod::l_get_perlin(lua_State *L) int ModApiEnvMod::l_get_perlin(lua_State *L)
{ {
@ -604,7 +604,7 @@ int ModApiEnvMod::l_get_perlin(lua_State *L)
return 1; return 1;
} }
// minetest.get_perlin_map(noiseparams, size) // get_perlin_map(noiseparams, size)
// returns world-specific PerlinNoiseMap // returns world-specific PerlinNoiseMap
int ModApiEnvMod::l_get_perlin_map(lua_State *L) int ModApiEnvMod::l_get_perlin_map(lua_State *L)
{ {
@ -623,7 +623,7 @@ int ModApiEnvMod::l_get_perlin_map(lua_State *L)
return 1; return 1;
} }
// minetest.get_voxel_manip() // get_voxel_manip()
// returns voxel manipulator // returns voxel manipulator
int ModApiEnvMod::l_get_voxel_manip(lua_State *L) int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
{ {
@ -638,7 +638,7 @@ int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
return 1; return 1;
} }
// minetest.clear_objects() // clear_objects()
// clear all objects in the environment // clear all objects in the environment
int ModApiEnvMod::l_clear_objects(lua_State *L) int ModApiEnvMod::l_clear_objects(lua_State *L)
{ {
@ -648,7 +648,7 @@ int ModApiEnvMod::l_clear_objects(lua_State *L)
return 0; return 0;
} }
// minetest.line_of_sight(pos1, pos2, stepsize) -> true/false, pos // line_of_sight(pos1, pos2, stepsize) -> true/false, pos
int ModApiEnvMod::l_line_of_sight(lua_State *L) { int ModApiEnvMod::l_line_of_sight(lua_State *L) {
float stepsize = 1.0; float stepsize = 1.0;
@ -673,7 +673,7 @@ int ModApiEnvMod::l_line_of_sight(lua_State *L) {
return 1; return 1;
} }
// minetest.find_path(pos1, pos2, searchdistance, // find_path(pos1, pos2, searchdistance,
// max_jump, max_drop, algorithm) -> table containing path // max_jump, max_drop, algorithm) -> table containing path
int ModApiEnvMod::l_find_path(lua_State *L) int ModApiEnvMod::l_find_path(lua_State *L)
{ {
@ -716,7 +716,7 @@ int ModApiEnvMod::l_find_path(lua_State *L)
return 0; return 0;
} }
// minetest.spawn_tree(pos, treedef) // spawn_tree(pos, treedef)
int ModApiEnvMod::l_spawn_tree(lua_State *L) int ModApiEnvMod::l_spawn_tree(lua_State *L)
{ {
GET_ENV_PTR; GET_ENV_PTR;
@ -765,7 +765,7 @@ int ModApiEnvMod::l_spawn_tree(lua_State *L)
return 1; return 1;
} }
// minetest.transforming_liquid_add(pos) // transforming_liquid_add(pos)
int ModApiEnvMod::l_transforming_liquid_add(lua_State *L) int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
{ {
GET_ENV_PTR; GET_ENV_PTR;
@ -775,7 +775,7 @@ int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
return 1; return 1;
} }
// minetest.forceload_block(blockpos) // forceload_block(blockpos)
// blockpos = {x=num, y=num, z=num} // blockpos = {x=num, y=num, z=num}
int ModApiEnvMod::l_forceload_block(lua_State *L) int ModApiEnvMod::l_forceload_block(lua_State *L)
{ {
@ -786,7 +786,7 @@ int ModApiEnvMod::l_forceload_block(lua_State *L)
return 0; return 0;
} }
// minetest.forceload_free_block(blockpos) // forceload_free_block(blockpos)
// blockpos = {x=num, y=num, z=num} // blockpos = {x=num, y=num, z=num}
int ModApiEnvMod::l_forceload_free_block(lua_State *L) int ModApiEnvMod::l_forceload_free_block(lua_State *L)
{ {

@ -25,134 +25,134 @@ with this program; if not, write to the Free Software Foundation, Inc.,
class ModApiEnvMod : public ModApiBase { class ModApiEnvMod : public ModApiBase {
private: private:
// minetest.set_node(pos, node) // set_node(pos, node)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
static int l_set_node(lua_State *L); static int l_set_node(lua_State *L);
static int l_add_node(lua_State *L); static int l_add_node(lua_State *L);
// minetest.remove_node(pos) // remove_node(pos)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
static int l_remove_node(lua_State *L); static int l_remove_node(lua_State *L);
// minetest.swap_node(pos, node) // swap_node(pos, node)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
static int l_swap_node(lua_State *L); static int l_swap_node(lua_State *L);
// minetest.get_node(pos) // get_node(pos)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
static int l_get_node(lua_State *L); static int l_get_node(lua_State *L);
// minetest.get_node_or_nil(pos) // get_node_or_nil(pos)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
static int l_get_node_or_nil(lua_State *L); static int l_get_node_or_nil(lua_State *L);
// minetest.get_node_light(pos, timeofday) // get_node_light(pos, timeofday)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
// timeofday: nil = current time, 0 = night, 0.5 = day // timeofday: nil = current time, 0 = night, 0.5 = day
static int l_get_node_light(lua_State *L); static int l_get_node_light(lua_State *L);
// minetest.place_node(pos, node) // place_node(pos, node)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
static int l_place_node(lua_State *L); static int l_place_node(lua_State *L);
// minetest.dig_node(pos) // dig_node(pos)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
static int l_dig_node(lua_State *L); static int l_dig_node(lua_State *L);
// minetest.punch_node(pos) // punch_node(pos)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
static int l_punch_node(lua_State *L); static int l_punch_node(lua_State *L);
// minetest.get_node_max_level(pos) // get_node_max_level(pos)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
static int l_get_node_max_level(lua_State *L); static int l_get_node_max_level(lua_State *L);
// minetest.get_node_level(pos) // get_node_level(pos)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
static int l_get_node_level(lua_State *L); static int l_get_node_level(lua_State *L);
// minetest.set_node_level(pos) // set_node_level(pos)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
static int l_set_node_level(lua_State *L); static int l_set_node_level(lua_State *L);
// minetest.add_node_level(pos) // add_node_level(pos)
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
static int l_add_node_level(lua_State *L); static int l_add_node_level(lua_State *L);
// minetest.get_meta(pos) // get_meta(pos)
static int l_get_meta(lua_State *L); static int l_get_meta(lua_State *L);
// minetest.get_node_timer(pos) // get_node_timer(pos)
static int l_get_node_timer(lua_State *L); static int l_get_node_timer(lua_State *L);
// minetest.add_entity(pos, entityname) -> ObjectRef or nil // add_entity(pos, entityname) -> ObjectRef or nil
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
static int l_add_entity(lua_State *L); static int l_add_entity(lua_State *L);
// minetest.add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
// pos = {x=num, y=num, z=num} // pos = {x=num, y=num, z=num}
static int l_add_item(lua_State *L); static int l_add_item(lua_State *L);
// minetest.get_player_by_name(name) // get_player_by_name(name)
static int l_get_player_by_name(lua_State *L); static int l_get_player_by_name(lua_State *L);
// minetest.get_objects_inside_radius(pos, radius) // get_objects_inside_radius(pos, radius)
static int l_get_objects_inside_radius(lua_State *L); static int l_get_objects_inside_radius(lua_State *L);
// minetest.set_timeofday(val) // set_timeofday(val)
// val = 0...1 // val = 0...1
static int l_set_timeofday(lua_State *L); static int l_set_timeofday(lua_State *L);
// minetest.get_timeofday() -> 0...1 // get_timeofday() -> 0...1
static int l_get_timeofday(lua_State *L); static int l_get_timeofday(lua_State *L);
// minetest.get_gametime() // get_gametime()
static int l_get_gametime(lua_State *L); static int l_get_gametime(lua_State *L);
// minetest.find_node_near(pos, radius, nodenames) -> pos or nil // find_node_near(pos, radius, nodenames) -> pos or nil
// nodenames: eg. {"ignore", "group:tree"} or "default:dirt" // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
static int l_find_node_near(lua_State *L); static int l_find_node_near(lua_State *L);
// minetest.find_nodes_in_area(minp, maxp, nodenames) -> list of positions // find_nodes_in_area(minp, maxp, nodenames) -> list of positions
// nodenames: eg. {"ignore", "group:tree"} or "default:dirt" // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
static int l_find_nodes_in_area(lua_State *L); static int l_find_nodes_in_area(lua_State *L);
// minetest.get_perlin(seeddiff, octaves, persistence, scale) // get_perlin(seeddiff, octaves, persistence, scale)
// returns world-specific PerlinNoise // returns world-specific PerlinNoise
static int l_get_perlin(lua_State *L); static int l_get_perlin(lua_State *L);
// minetest.get_perlin_map(noiseparams, size) // get_perlin_map(noiseparams, size)
// returns world-specific PerlinNoiseMap // returns world-specific PerlinNoiseMap
static int l_get_perlin_map(lua_State *L); static int l_get_perlin_map(lua_State *L);
// minetest.get_voxel_manip() // get_voxel_manip()
// returns world-specific voxel manipulator // returns world-specific voxel manipulator
static int l_get_voxel_manip(lua_State *L); static int l_get_voxel_manip(lua_State *L);
// minetest.clear_objects() // clear_objects()
// clear all objects in the environment // clear all objects in the environment
static int l_clear_objects(lua_State *L); static int l_clear_objects(lua_State *L);
// minetest.spawn_tree(pos, treedef) // spawn_tree(pos, treedef)
static int l_spawn_tree(lua_State *L); static int l_spawn_tree(lua_State *L);
// minetest.line_of_sight(pos1, pos2, stepsize) -> true/false // line_of_sight(pos1, pos2, stepsize) -> true/false
static int l_line_of_sight(lua_State *L); static int l_line_of_sight(lua_State *L);
// minetest.find_path(pos1, pos2, searchdistance, // find_path(pos1, pos2, searchdistance,
// max_jump, max_drop, algorithm) -> table containing path // max_jump, max_drop, algorithm) -> table containing path
static int l_find_path(lua_State *L); static int l_find_path(lua_State *L);
// minetest.transforming_liquid_add(pos) // transforming_liquid_add(pos)
static int l_transforming_liquid_add(lua_State *L); static int l_transforming_liquid_add(lua_State *L);
// minetest.forceload_block(blockpos) // forceload_block(blockpos)
// forceloads a block // forceloads a block
static int l_forceload_block(lua_State *L); static int l_forceload_block(lua_State *L);
// minetest.forceload_free_block(blockpos) // forceload_free_block(blockpos)
// stops forceloading a position // stops forceloading a position
static int l_forceload_free_block(lua_State *L); static int l_forceload_free_block(lua_State *L);

@ -361,7 +361,7 @@ int InvRef::l_remove_item(lua_State *L)
return 1; return 1;
} }
// get_location() -> location (like minetest.get_inventory(location)) // get_location() -> location (like get_inventory(location))
int InvRef::l_get_location(lua_State *L) int InvRef::l_get_location(lua_State *L)
{ {
NO_MAP_LOCK_REQUIRED; NO_MAP_LOCK_REQUIRED;

@ -101,7 +101,7 @@ private:
// Returns the items that were actually removed // Returns the items that were actually removed
static int l_remove_item(lua_State *L); static int l_remove_item(lua_State *L);
// get_location() -> location (like minetest.get_inventory(location)) // get_location() -> location (like get_inventory(location))
static int l_get_location(lua_State *L); static int l_get_location(lua_State *L);
public: public:

@ -234,7 +234,7 @@ int LuaItemStack::l_is_known(lua_State *L)
} }
// get_definition(self) -> table // get_definition(self) -> table
// Returns the item definition table from minetest.registered_items, // Returns the item definition table from registered_items,
// or a fallback one (name="unknown") // or a fallback one (name="unknown")
int LuaItemStack::l_get_definition(lua_State *L) int LuaItemStack::l_get_definition(lua_State *L)
{ {
@ -242,8 +242,8 @@ int LuaItemStack::l_get_definition(lua_State *L)
LuaItemStack *o = checkobject(L, 1); LuaItemStack *o = checkobject(L, 1);
ItemStack &item = o->m_stack; ItemStack &item = o->m_stack;
// Get minetest.registered_items[name] // Get registered_items[name]
lua_getglobal(L, "minetest"); lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_items"); lua_getfield(L, -1, "registered_items");
luaL_checktype(L, -1, LUA_TTABLE); luaL_checktype(L, -1, LUA_TTABLE);
lua_getfield(L, -1, item.name.c_str()); lua_getfield(L, -1, item.name.c_str());

@ -85,7 +85,7 @@ private:
static int l_is_known(lua_State *L); static int l_is_known(lua_State *L);
// get_definition(self) -> table // get_definition(self) -> table
// Returns the item definition table from minetest.registered_items, // Returns the item definition table from core.registered_items,
// or a fallback one (name="unknown") // or a fallback one (name="unknown")
static int l_get_definition(lua_State *L); static int l_get_definition(lua_State *L);

@ -78,7 +78,7 @@ struct EnumString ModApiMapgen::es_Rotation[] =
}; };
// minetest.get_mapgen_object(objectname) // get_mapgen_object(objectname)
// returns the requested object used during map generation // returns the requested object used during map generation
int ModApiMapgen::l_get_mapgen_object(lua_State *L) int ModApiMapgen::l_get_mapgen_object(lua_State *L)
{ {
@ -181,7 +181,7 @@ int ModApiMapgen::l_get_mapgen_object(lua_State *L)
return 0; return 0;
} }
// minetest.set_mapgen_params(params) // set_mapgen_params(params)
// set mapgen parameters // set mapgen parameters
int ModApiMapgen::l_set_mapgen_params(lua_State *L) int ModApiMapgen::l_set_mapgen_params(lua_State *L)
{ {
@ -225,7 +225,7 @@ int ModApiMapgen::l_set_mapgen_params(lua_State *L)
return 0; return 0;
} }
// minetest.set_noiseparam_defaults({np1={noise params}, ...}) // set_noiseparam_defaults({np1={noise params}, ...})
// set default values for noise parameters if not present in global settings // set default values for noise parameters if not present in global settings
int ModApiMapgen::l_set_noiseparam_defaults(lua_State *L) int ModApiMapgen::l_set_noiseparam_defaults(lua_State *L)
{ {

@ -24,15 +24,15 @@ with this program; if not, write to the Free Software Foundation, Inc.,
class ModApiMapgen : public ModApiBase { class ModApiMapgen : public ModApiBase {
private: private:
// minetest.get_mapgen_object(objectname) // get_mapgen_object(objectname)
// returns the requested object used during map generation // returns the requested object used during map generation
static int l_get_mapgen_object(lua_State *L); static int l_get_mapgen_object(lua_State *L);
// minetest.set_mapgen_params(params) // set_mapgen_params(params)
// set mapgen parameters // set mapgen parameters
static int l_set_mapgen_params(lua_State *L); static int l_set_mapgen_params(lua_State *L);
// minetest.set_noiseparam_defaults({np1={noise params}, ...}) // set_noiseparam_defaults({np1={noise params}, ...})
static int l_set_noiseparam_defaults(lua_State *L); static int l_set_noiseparam_defaults(lua_State *L);
// set_gen_notify(flagstring) // set_gen_notify(flagstring)

@ -341,7 +341,7 @@ int ModApiServer::l_show_formspec(lua_State *L)
int ModApiServer::l_get_current_modname(lua_State *L) int ModApiServer::l_get_current_modname(lua_State *L)
{ {
NO_MAP_LOCK_REQUIRED; NO_MAP_LOCK_REQUIRED;
lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname"); lua_getfield(L, LUA_REGISTRYINDEX, "current_modname");
return 1; return 1;
} }

@ -28,9 +28,8 @@ class ModApiUtil : public ModApiBase {
private: private:
/* /*
NOTE: NOTE:
The functions in this module are available through The functions in this module are available in the in-game API
minetest.<function> in the in-game API as well as as well as in the mainmenu API.
engine.<function> in the mainmenu API
All functions that don't require either a Server or All functions that don't require either a Server or
GUIEngine instance should be in here. GUIEngine instance should be in here.

@ -19,7 +19,6 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "scripting_game.h" #include "scripting_game.h"
#include "server.h" #include "server.h"
#include "filesys.h"
#include "log.h" #include "log.h"
#include "cpp_api/s_internal.h" #include "cpp_api/s_internal.h"
#include "lua_api/l_base.h" #include "lua_api/l_base.h"
@ -52,17 +51,9 @@ GameScripting::GameScripting(Server* server)
//TODO add security //TODO add security
luaL_openlibs(getStack());
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
lua_pushstring(L, DIR_DELIM); lua_getglobal(L, "core");
lua_setglobal(L, "DIR_DELIM");
// Create the main minetest table
lua_newtable(L);
lua_setglobal(L, "minetest");
lua_getglobal(L, "minetest");
int top = lua_gettop(L); int top = lua_gettop(L);
lua_newtable(L); lua_newtable(L);

@ -21,7 +21,6 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "mods.h" #include "mods.h"
#include "porting.h" #include "porting.h"
#include "log.h" #include "log.h"
#include "filesys.h"
#include "cpp_api/s_internal.h" #include "cpp_api/s_internal.h"
#include "lua_api/l_base.h" #include "lua_api/l_base.h"
#include "lua_api/l_mainmenu.h" #include "lua_api/l_mainmenu.h"
@ -41,18 +40,11 @@ MainMenuScripting::MainMenuScripting(GUIEngine* guiengine)
//TODO add security //TODO add security
luaL_openlibs(getStack());
SCRIPTAPI_PRECHECKHEADER SCRIPTAPI_PRECHECKHEADER
lua_newtable(L); lua_getglobal(L, "core");
lua_setglobal(L, "engine");
lua_getglobal(L, "engine");
int top = lua_gettop(L); int top = lua_gettop(L);
lua_pushstring(L, DIR_DELIM);
lua_setglobal(L, "DIR_DELIM");
lua_newtable(L); lua_newtable(L);
lua_setglobal(L, "gamedata"); lua_setglobal(L, "gamedata");