The script is supposed to check if the ingredients table match to the recipes table and if so it prints madepotion but it doesnt do it properly for some reason. The ingredients table doesn’t match the recipe table but it still prints madepotion
function checkrecipe(recipe,result)
for ing,amount in pairs(result) do
if recipe[ing] then
if recipe[ing] ~= amount then
return false
end
else
return false
end
end
return true
end
local recipes = {
["Health Potion"] = {["Scroom"] = 2, ["LavaFlower"] = 1},
["Tespian Exilir"] = {["Moss Plant"] = 2, ["Scroom"] = 1, ["LavaFlower"] = 1}
}
local ingredients = "Scroom,LavaFlower"
local tab = string.split(ingredients, ",")
local result = {}
for i,v in pairs(tab) do
if not result[v] then
result[v] = 1
else
result[v] = result[v] + 1
end
end
local madepotion = nil
for i,v in pairs(recipes) do
if checkrecipe(v,result) then
madepotion = i
print("madepotion")
break
end
end
if not madepotion then
print("explode")
end
1 Like
Uhhhh the top of your script got cut off
Reworking your code a little, this will work nicely:
local function check_potion(recipe, result)
for ingredient, amount in pairs(recipe) do
if result[ingredient] ~= amount then
return false;
end
end
return true;
end
local recipes = {
["Health Potion"] = {["Scroom"] = 2, ["LavaFlower"] = 1},
["Tespian Exilir"] = {["Moss Plant"] = 2, ["Scroom"] = 1, ["LavaFlower"] = 1}
}
local result = {["Scroom"] = 1, ["LavaFlower"] = 1}
local made_potion = nil;
for potion_name, recipe in pairs(recipes) do
if check_potion(recipe, result) then
made_potion = potion_name;
print("madepotion");
break;
end
end
if not made_potion then
print("explode")
end
Note how I re-formatted your result variable from a string to a dictionary so that it was in the same data format as the recipes themselves. This makes the code easier to work with. The checking algorithm should also be pretty simplistic. It just goes through the recipe and checks each ingredient in the result, until one is not identical, in which case it returns false. If it gets through without returning it’ll then return true (recipe and result are identical).
That wouldn’t work for me though i use the string split because im going to get the strings from a value in that contains the ingredients and can be manipulated by the player. (sorry for late response)