physics: Add sanity checks and minor optimizations (#650)

- Throw error if an unsupported attribute is encountered.
- Throw errors for invalid function arguments.
- Optimize out attributes with a value of 1.
This commit is contained in:
ANAND 2020-09-22 21:20:27 +05:30 committed by GitHub
parent ec06b8edde
commit 7793e76890
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,6 +1,11 @@
physics = {}
local players = {}
local default_overrides = {
speed = 1,
jump = 1,
gravity = 1
}
minetest.register_on_joinplayer(function(player)
players[player:get_player_name()] = {}
@ -13,11 +18,7 @@ end)
local function update(name)
assert(players[name])
local player = minetest.get_player_by_name(name)
local override = {
speed = 1,
jump = 1,
gravity = 1
}
local override = table.copy(default_overrides)
for _, layer in pairs(players[name]) do
for attr, val in pairs(layer) do
@ -28,20 +29,40 @@ local function update(name)
player:set_physics_override(override)
end
function physics.set(pname, name, modifiers)
if not players[pname] then
function physics.set(name, layer, modifiers)
-- Basic sanity checks
assert(
type(name) == "string" and type(layer) == "string" and type(modifiers) == "table",
"physics.set: Invalid function arguments!"
)
if not players[name] then
return
end
players[pname][name] = modifiers
update(pname)
for attr, val in pairs(modifiers) do
-- Throw error if an unsupported attribute is encountered
assert(default_overrides[attr], "physics: Unsupported attribute!")
-- Remove an attribute if its value is 1
if val == 1 then
modifiers[attr] = nil
end
end
players[name][layer] = modifiers
update(name)
end
function physics.remove(pname, name)
if not players[pname] then
function physics.remove(name, layer)
-- Basic sanity checks
assert(type(name) == "string" and type(layer) == "string",
"physics.remove: Invalid function arguments!")
if not players[name] then
return
end
players[pname][name] = nil
update(pname)
players[name][layer] = nil
update(name)
end