New: Nitro Boost our Discord server and receive full donation perks here on the website! Join the Scripting Helpers Discord Server to learn more! You can also Support on Patreon as always.
Ad
Still have questions? Join our Discord server and get real time help.
Log in to vote
0

How to use math.random w/ in pairs?

Asked by
ItsMeKlc 235 Moderation Voter
4 years ago

I'm trying to choose a random song and it's title at the same time, but it isn't working... What am I doing wrong?

    local songs = {Friday = "268763467",
                    ["The Song of the Cebu"] = "142570249",
                    Problem = "261244793",
                    Bills = "165508381"
                    }

    local song = songs[math.random(1,#in pairs(songs))
    music.SoundId =("http://www.roblox.com/asset/?id="..song)
    music:Play()
0
local song = songs[math.random(1,#songs)] TheDeadlyPanther 2437 — 4y

1 answer

Log in to vote
0
Answered by 4 years ago

The pairs function returns all the keys and values of the argument table, math.random returns a random integer. For this reason, you can't directly index a value at a non-integer key with a value generated from math.random. Here's a potential workaround:

function obtainRandomKeyValuePair(tab)
    local randIndex = math.random(1, #tab);
    local curIndex = 1;

    for k, v in pairs(songs) do
        if curIndex >= randIndex then
            return k, v;
        end

        curIndex = curIndex + 1;
    end
end

You would then call the function with:

local key, val = obtainRandomKeyValuePair(songs);

EDIT: Apparently the length operator doesn't work on tables with non-numeric indices. That's really poor design. At any rate, I would switch to a 2D table. Here's an example:

local songs = {
    titles = {
        "Friday",
        "The Song of the Cebu",
        "Problem",
        "Bills"
    },
    ids = {
        "268763467",
        "142570249",
        "261244793",
        "165508381"
    }
};

local randIndex = math.random(1, #songs.titles);
local title = songs.titles[randIndex];
local id = songs.ids[randIndex];
0
output says " Players.Player.PlayerGui.GUI.Everything.Popups.Settings.LocalScript:17: bad argument #2 to 'random' (interval is empty)" :l ItsMeKlc 235 — 4y
0
@legokendall Sorry, Lua is stupid. See my edit. DreadPirateRobux 655 — 4y
0
#tab will not count all keys -- just the ones 1, 2, 3, ... up to some number. It will be 0 on the given table. You have to count them yourself (with two `for` loops) BlueTaslem 17864 — 4y
Ad

Answer this question