cleaned up sethome

Cleaned up the code, set it to :write() only once not in the loop, removed redundant callbacks and removed the concentrations.
This commit is contained in:
pinkysnowman 2015-09-22 22:43:25 -04:00 committed by crazyginger72
parent 24578ca968
commit 1df9222aef

View file

@ -2,64 +2,53 @@ local homes_file = minetest.get_worldpath() .. "/homes"
local homepos = {} local homepos = {}
local function loadhomes() local function loadhomes()
local input = io.open(homes_file, "r") local input = io.open(homes_file, "r")
if input then if input then
repeat repeat
local x = input:read("*n") local x = input:read("*n")
if x == nil then if x == nil then
break break
end end
local y = input:read("*n") local y = input:read("*n")
local z = input:read("*n") local z = input:read("*n")
local name = input:read("*l") local name = input:read("*l")
homepos[name:sub(2)] = {x = x, y = y, z = z} homepos[name:sub(2)] = {x = x, y = y, z = z}
until input:read(0) == nil until input:read(0) == nil
io.close(input) io.close(input)
else end
homepos = {}
end
end end
loadhomes() loadhomes()
minetest.register_privilege("home", "Can use /sethome and /home") minetest.register_privilege("home", "Can use /sethome and /home")
local changed = false minetest.register_chatcommand("home", {
description = "Teleport you to your home point",
minetest.register_chatcommand("home", { privs = {home=true},
description = "Teleport you to your home point", func = function(name)
privs = {home=true}, local player = minetest.get_player_by_name(name)
func = function(name) if player and homepos[name] then
local player = minetest.get_player_by_name(name) player:setpos(homepos[name])
if player == nil then return true, "Teleported to home!"
-- just a check to prevent the server crashing else
return false return false, "Set a home using /sethome"
end end
if homepos[player:get_player_name()] then end
player:setpos(homepos[player:get_player_name()])
minetest.chat_send_player(name, "Teleported to home!")
else
minetest.chat_send_player(name, "Set a home using /sethome")
end
end,
}) })
minetest.register_chatcommand("sethome", { minetest.register_chatcommand("sethome", {
description = "Set your home point", description = "Set your home point",
privs = {home=true}, privs = {home=true},
func = function(name) func = function(name)
local player = minetest.get_player_by_name(name) local pos = minetest.get_player_by_name(name):getpos()
local pos = player:getpos() local output = io.open(homes_file, "w")
homepos[player:get_player_name()] = pos homepos[name] = pos
minetest.chat_send_player(name, "Home set!") local data = {}
changed = true for i, v in pairs(homepos) do
if changed then table.insert(data,string.format("%.1f %.1f %.1f %s", v.x,v.y,v.z,i))
local output = io.open(homes_file, "w") end
for i, v in pairs(homepos) do output:write(table.concat(data),"\n")
output:write(v.x.." "..v.y.." "..v.z.." "..i.."\n") io.close(output)
end return true, "Home set!"
io.close(output) end
changed = false })
end
end,
})