Can I select value from table based on function input?

Viewed 84

I would like to know if it's possible to select a value from a table, based on the argument of a function.

I've tried setting the value statically, and that returns the value. I would just like to do it using function arguments.


function CheckWeapon(ped, attachment)
    for k,v in pairs(weapons)do
        if GetHashKey(k) == GetSelectedPedWeapon(ped) then
            print(v.attachment)
            return v.attachment -- This needs to be based on the 
                                -- argument "attachment"
        end
    end
    return false
end

I would expect that if I supplied the argument "silencer" to this function, I would receive the corresponding value for silencer in the table. Instead it's nil. If I type return v.silencer manually, it works though.

1 Answers

In Lua you can index a table 2 ways.

As you have done you can use . such as sometable.key but this is just syntactic sugar for the other method of indexing, sometable["key"] both of these use the string key to index the table.

your code could look like:

function CheckWeapon(ped, key)-- where key is a string ie: "attachment"
    for k,v in pairs(weapons)do
        if GetHashKey(k) == GetSelectedPedWeapon(ped) then
            print(v[key])
            return v[key]
        end
    end
    return false
end

using the sometable["key"] option also allows for keys that could not be accessed with . such as

sometable["my key"] -- note the space
sometable["1st_key"] -- note it begins with a number
Related