[TIP] Check if items are eatable

User avatar
AiTechEye
Member
 
Posts: 545
Joined: Fri May 29, 2015 21:14

[TIP] Check if items are eatable

by AiTechEye » Sun Jan 01, 2017 11:41

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: 476
Joined: Sun Sep 04, 2016 15:15
GitHub: bell07

Re: [TIP] Check if items are eatable

by bell07 » Mon Feb 27, 2017 22:44

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: 3064
Joined: Mon Sep 24, 2012 15:01
GitHub: Wuzzy2
IRC: Wuzzy
In-game: Wuzzy

Re: [TIP] Check if items are eatable

by Wuzzy » Fri Mar 03, 2017 01:50

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.
My projects: MineClone 2. Hades Revisited. Help modpack. A ton of other mods, see here.
 


Return to Modding Discussion



Who is online

Users browsing this forum: No registered users and 2 guests