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

How could i print a random variable and see if its set to true or false?

Asked by
oSyM8V3N 429 Moderation Voter
7 years ago
--//Dictionary
local keyDictionary = {
    ["Q"] = false ,
    ["E"] = false ,
    ["R"] = false ,
    ["T"] = false
}

for i = 1, math.random(keyDictionary) do
    print(math.random(keyDictionary))
end

I had help earlier on, but i still don't get it since this is my first time using tables/dictionary. But i'm just confused with for example : printing either 'Q, E, R or T' if picked and prints again if its true or false.

1 answer

Log in to vote
2
Answered by 7 years ago

When you create a dictionary, you're essentially changing the index from integers (1, 2, 3) to strings or other values that Lua allows ("Apple", "Banana", "Cherry").

As for your script, there are a few problems.

  • math.random(), requires an integer value. keyDictionary is clearly a Dictionary value so that won't work with that function.

  • So it seems you were trying to print the index of the table with your print statement. If you used math.random() correctly, that would still only print an integer and would not have provided the results you wanted.

  • Another problem that may have happened is you trying to index the Dictionary with an integer. An example:

keyDictionary[math.random(1, 4)]

This would not have found the value you wanted, since as I said before, the indexes are now strings ("Q", "E", etc), not integers (1, 2, 3, etc).

Now I'll explain a way to complete the task that you intended to complete.

local keyDictionary = {
    ["Q"] = false,
    ["E"] = false,
    ["R"] = false,
    ["T"] = false
} -- Dictionary Created

local dictionaryIndex = {"Q", "E", "R", "T"} -- I recommend a function to create this table, rather hard coding it 

--[[ The length of a dictionary cannot be found with the # operator, so we'll use a function to find the length ]]--

local function findLength(dictionary)
    total = 0

    for i,v in pairs (keyDictionary) do
        total = total+1
    end

    return total
end

--[[ Now that we have the amount of values, we can now use it to find a random value to find our index ]]--

local function findRandomIndex()
    local index = dictionaryIndex[math.random(findLength(keyDictionary))]

    -- We have our index, now to find the value in our dictionary.

    local value = keyDictionary[index]

    return index,value
end

And there you are. This script returns a random index and the corresponding values. There may be a more efficient way in doing this, unsure if there is a shortcut in finding the length of dictionaries, but regardless, this should help your understanding of dictionaries.

If you have any questions, please feel free to ask. :)

0
Ohh, alright i think i got it now. Thanks for the help! :) oSyM8V3N 429 — 7y
0
If i have any questions i'll let you know oSyM8V3N 429 — 7y
Ad

Answer this question