✓ Accepted answer
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];
1 comment
local song = songs[math.random(1,#songs)]