Buggy example code to make tool break after n uses
Chapter 7, section "Wear" shows code that supposedly shows how you can make a tool break after 10 uses. However, the code shown is buggy.
Tools can have wear; wear shows a progress bar and makes the tool break when completely worn. Wear is a number out of 65535; the higher it is, > the more worn the tool is.
Wear can be manipulated using add_wear(), get_wear(), and set_wear(wear).
local stack = ItemStack("default:pick_mese") local max_uses = 10 -- This is done automatically when you use a tool that digs things -- It increases the wear of an item by one use. stack:add_wear(65535 / (max_uses - 1))
This code is wrong and based on an old tricky Minetest bug I fixed. For an arbitrary value of max_uses
, the actual number of tool uses will be wrong due to rounding error AND a off-by-1 error and gets worse the larger the number becomes. I discussed this in length in https://github.com/minetest/minetest/pull/11110 and https://github.com/minetest/minetest/pull/12047. Anyway, the correct example code would be:
local stack = ItemStack("default:pick_mese") local max_uses = 10 stack:add_wear_by_uses(max_uses)
Because the add_wear_by_uses
does the correct (but non-obvious) math to do this calculation correctly and makes sure the tool breaks after exactly max_uses
(assuming no other wear manipulation was done, of course).