Home > Mobile >  Variable with multiple values to use
Variable with multiple values to use

Time:06-14

Im editing a script for fivem and Im trying to store multiple values into a variable then using an if statement to see if a player has one of the values in his inventory. So far i have this

Config.ItemVapeLiquid = 'liquid', 'liquidice', 'liquidberry'

the problem I'm having is it only runs when the player has 'liquid' on them, when they don't, it returns a nil value even if they have 'liquidice' or 'liquidberry'. what im trying to get do is:

Config.ItemVapeLiquid = 'liquid', 'liquidice', 'liquidberry'

if the player has a value from ItemVapeLiquid then
  allow player to add liquid

I want it to check all the values in the variable before returning nil as it seems to be checking 1 value and returning nil if its not in the inventory

I appreciate any help!

CodePudding user response:

While the first line compiles, it will ignore any unassigned values ('liquidice', 'liquidberry').

It expects three variables:

local a, b, c = 'liquid', 'liquidice', 'liquidberry'

Since that's impractical you need an array instead, as well as a function to search within that array:

Config.ItemVapeLiquid = {'liquid', 'liquidice', 'liquidberry'}

function check(array, value)
    for _,v in ipairs(array) do
        if v == value then
            return true
        end
    end
    return false
end

print(check(Config.ItemVapeLiquid, 'liquid'))
print(check(Config.ItemVapeLiquid, 'liquidice'))
print(check(Config.ItemVapeLiquid, 'liquidberry'))
print(check(Config.ItemVapeLiquid, 'something'))
true
true
true
false

If you plan on calling checks more often, consider transforming the array into a set instead, since this is much faster:

-- feel free to make an array-to-set function for this
Config.ItemVapeLiquid = {
    ['liquid'] = true,
    ['liquidice'] = true,
    ['liquidberry'] = true
}

print(Config.ItemVapeLiquid['liquid'])
print(Config.ItemVapeLiquid['liquidice'])
print(Config.ItemVapeLiquid['liquidberry'])
print(Config.ItemVapeLiquid['something'])
true
true
true
nil

Notice that a missing element is now nil, which evaluates to false and is therefore usually fine. If you really need a false value, append:

Config.ItemVapeLiquid["something"] or false
  • Related