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

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

Asked by 4 years ago

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

Log in to vote
1
Answered by 4 years ago

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
THANK YOU! YOU ARE A LIFE SAVER! Nistrict 44 — 4y
Ad
Log in to vote
1
Answered by
oreoollie 649 Moderation Voter
4 years ago
Edited 4 years ago

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!

Answer this question