math.randomseed(os.time()) local sounds = script:GetChildren() local playMusic while wait(1) do playMusic() end function playMusic() local ran = math.random(#sounds) sounds[ran]:Play() if not sounds[ran].IsPlaying then return end end
I forward declared function playMusic before the while loop but I got this error: 22:13:00.400 - ServerScriptService.Main Music:7: attempt to call local 'playMusic' (a nil value)
It is like any other programming language. It is like someone asking you what "print('Hello world!')" means and expecting you to know what it is, and afterwards telling you what that means. It is like asking why the following does not print 6.
local var = 3 print(var) local var = 6
Code runs from up to down, not just picking a random line and running it. So, once it realises what playMusic() means it is too late, as the script already gave an error about how playMusic() is not defined.
This is why some people like defining variables and functions at the beginning at the script
local something = 'a' function nothing() return end print(something, nothing())
but if you don't, until you realise you are using something a lot and want a variable for it. You already have working code, but if you had a variable, it would save some time.
Hope this helps!
Your problem is that your code never actually reaches the definition of the playMusic
function.
Either spawn
the loop like so:
math.randomseed(os.time()) local sounds = script:GetChildren() local playMusic spawn(function() while wait(1) do playMusic() end end) function playMusic() local ran = math.random(#sounds) sounds[ran]:Play() if not sounds[ran].IsPlaying then return end end
Or don't bother with forward-declaration in this case.
I often define my functions like this
local functionOne, functionTwo, functionThree functionOne = function() print("Hello, World!") end functionTwo = function() functionThree() end functionThree = function() print("Hello, World") end functionOne() functionTwo()
Although this is comparable to the confusion in your code my initial calls don't actually occur until all functions are declared and defined. In your code as hiim & Shadi also explain that although you have declared the variable that the function value will be assigned to... You haven't actually defined what it does, so the compiler is going "lol wat mate there's no function assigned to this variable why you tryin' to call it?!".
I declare and define my functions separately purely so I don't have to worry about the order of the function definitions for cases in which I'm calling functions inside other functions... However, as is the only way you can code in RBX.Lua, all my actual processing is written further below in my Scripts.
You defined your function as a nil variable, then you defined it later, because of that you cannot call it.
Define the function first and then call it.