Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to fix error attempt to get length of a userdata value?

I have this script that will pick a random song from a folder in workspace and then play it.

local LobbyMusicFolder = game.workspace:WaitForChild("LobbyMusic")
LobbyMusicFolder:GetChildren()

local LobbyMusicChosen = LobbyMusicFolder[math.random(1,#LobbyMusicFolder)]

LobbyMusicChosen:Play()

2 answers

✓ Accepted answer

Hey, currently you're just giving it the folder in the 2nd argument of math.random. :)

This is why it's returning a userdata.

What you can do is, use this

lobbyMusicFolderGetChildren() ^ Gives you a table, which we can then use math.random on :D

local LobbyMusicFolder = game.workspace:WaitForChild("LobbyMusic")
local lobbyMusicChosen = lobbyMusicFolderGetChildren()[math.random(1, #lobbyMusicFolder:GetChildren())]

lobbyMusicChosen:Play()

If this helped, please mark it as answered, and upvote!

1 comment

1

THANK YOU! YOU ARE A LIFE SAVER!

It looks like you know Javascript. An important difference between Javascript and Lua is that methods in Lua usually don't modify the object they act on, rather they return the value. This problem is easily fixable by changing line 1 to

local LobbyMusicFolder = game.workspace:WaitForChild("LobbyMusic"):GetChildren()

I hope my answer helped you. Please remember to mark it as correct and upvote it if it solved your problem best!

This discussion is preserved as it was. New answers, comments, and votes are closed.