[TIP] Check if items are eatable

Post Reply
User avatar
AiTechEye
Member
Posts: 1000
Joined: Fri May 29, 2015 21:14
GitHub: AiTechEye
Location: Sweden

[TIP] Check if items are eatable

by AiTechEye » Post

Because its useful, and there have been questions about this before.

the function will return number of the hp change or nil.

Code: Select all

eatable=function(name)
	local def={
		minetest.registered_items[name],
		minetest.registered_nodes[name],
		minetest.registered_craftitems[name],
		minetest.registered_tools[name]
	}
	for _, ob in pairs(def) do
		if ob~=nil then
			local name,change=debug.getupvalue(ob.on_use, 1)
			if name~=nil and name=="hp_change" then
				return change
			end
		end
	end
	return nil
end

bell07
Member
Posts: 604
Joined: Sun Sep 04, 2016 15:15
GitHub: bell07

Re: [TIP] Check if items are eatable

by bell07 » Post

Thanks! It is I searched for! Now I have 2 additional grouping filter in smart_inventory ;-)

Code: Select all

filter.register_filter({
		name = "eatable",
		filter_func = function(def, name)
			if def.on_use then
				local name,change=debug.getupvalue(def.on_use, 1)
				if name~=nil and name=="hp_change" and change > 0 then
					return tostring(change)
				end
			end
		end
	})

filter.register_filter({
		name = "toxic",
		filter_func = function(def, name)
			if def.on_use then
				local name,change=debug.getupvalue(def.on_use, 1)
				if name~=nil and name=="hp_change" and change < 0 then
					return tostring(change)
				end
			end
		end
	})
A hint for you: you do not need to read minetest.registered_nodes, minetest.registered_craftitems, minetest.registered_tools. All items are in the registered_items table, with type="node","tool" or "craft" ;-)
So you can reduce your code to

Code: Select all

eatable=function(name)
   local ob = minetest.registered_items[name]
   if ob and ob.on_use then
      local name,change=debug.getupvalue(ob.on_use, 1)
      if name~=nil and name=="hp_change" then
         return change
      end
   end
   return nil
end

User avatar
Wuzzy
Member
Posts: 4804
Joined: Mon Sep 24, 2012 15:01
GitHub: Wuzzy2
IRC: Wuzzy
In-game: Wuzzy
Contact:

Re: [TIP] Check if items are eatable

by Wuzzy » Post

Any solution which involves the debug table should only be a temporary hack.
The real problem is that Minetest makes it very hard to figure out if an item is eatable. There is no standard parsable field, this is the problem, this needs to be fixed in Minetest.

Post Reply

Who is online

Users browsing this forum: No registered users and 9 guests