Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to check if table index is this string?

Asked by 8 years ago

How to check if index of a table is a string?

So for example, how to check if the index 1 of table "InvTable" is a string "Iron Ore"?

EDIT:

    if player.Smelting.Value == true then
        if getIndex(invtab, "Copper Ore") == true then  
             local copper = getIndex(invtab, "Copper Ore")      
                table.remove(invtab, copper)
                CheckForEmptyBox()
                local numb = selectedbox.Numb
                table.insert(invtab, numb.Value, "Copper Ingot")
                player.Smelting.Value = false
                player.Smeltwhat.Value = ""
        else print("Nope")
        end

this is the code im trying to use. It prints "Nope", even though im sure there is a value "Copper Ore" in the invtab table. What am i doing wrong?

No errors btw.

1 answer

Log in to vote
0
Answered by
Pyrondon 2089 Game Jam Winner Moderation Voter Community Moderator
8 years ago

This should return the spot in the table whatever you specify is in, and nil if none:

function getIndex(table, item)
    for i, v in pairs (table) do
        if v == item then
            return i
        end
    end
end

EDIT: I didn't include an example..

if getIndex(InvTable, "Iron Ore") ~= nil then
    -- Do stuff
else
    -- Do other stuff?

Hope this helped.

EDIT 2: The getIndex function returns which spot it's in, not a boolean value. So, it should look like this:

if player.Smelting.Value == true then
    if getIndex(invtab, "Copper Ore") ~= nil then 
         local copper = getIndex(invtab, "Copper Ore")      
            table.remove(invtab, copper)
            CheckForEmptyBox()
            local numb = selectedbox.Numb
            table.insert(invtab, numb.Value, "Copper Ingot")
            player.Smelting.Value = false
            player.Smeltwhat.Value = ""
    else print("Nope")
    end
0
Updated my post. User#11680 0 — 8y
Ad

Answer this question