Hi guys! I'm pretty new to LUA scripting, although I do have experience in C++, java, and i've recently been doing c# in Unity. I've been wanting to do a script where I can add a ParticleEmitter named SparkleAtmosphere to my baseplates, which are in workspace > FantasyPlates. I have multiple baseplates under FantasyPlates named BasePlate, and I tried writing a program to copy SparkleAtmosphere objects from Lighting into the baseplates when it is day, and removing them when it is night, but i'm horrific with LUA. I was wondering if anyone could look at my code and give me advice on what I could do to achieve this goal. Also, if possible, I would like to know what I could do to make my code look better or more readable, since my indenting style (especially for if statements) revolves around using brackets {}, but LUA uses "end" to tie things up, and it looks really weird. I would also like to know if all "if" and "else if" statements require an "end" or not, because I encountered some problems with that while scripting. Or rather, do I need to put an "end" every time I write a line of code that has blue words, such as "for" "while" "if"??? Thanks a bunch!
Here's my code:
local Time = game:service("Lighting") while true do if(Time:GetMinutesAfterMidnight() > 480)then if(Time:GetMinutesAfterMidnight() < 1065)then end else if(Time:GetMinutesAfterMidnight() >= 1065) then local k = game.Lighting:FindFirstChild("SparkleAtmosphere"):clone() for index, child in pairs(workspace.FantasyPlates:GetChildren()) do o = child.Name k.Parent = o end end else if(Time:GetMinutesAfterMidnight() < 480) then local k = game.Lighting:FindFirstChild("SparkleAtmosphere"):clone() for index, child in pairs(workspace.FantasyPlates:GetChildren()) do o = child.Name k.Parent = o end end wait(1) end -- between 480 and 1065 is "day"
Unlike most c-based languages, Lua does not require and 'ending' statement or symbol for if-elseif chains.
In fact, if
statements in Lua are very much akin to switch
statements in C.
The logic of your if statements is very... opaque. I've rewritten your code to be more readable, and to avoid writing the same code twice:
local Time = game:GetService("Lighting") --service is deprecated while true do if Time:GetMinutesAfterMidnight() < 480 or Time:GetMinutesAfterMidnight() > 1065 then local k = game.Lighting:FindFirstChild("SparkleAtmosphere"):Clone() --clone (lowercase) is deprecated for _, baseplate in pairs(workspace.FantasyPlates:GetChildren()) do --In Lua, it's common practice to use `_` for unused variables, as in this case. --Additionally, 'baseplate' is more descriptive than 'child. k:Clone().Parent = baseplate -- Parent is an 'object' value, and Name is a 'string'. ROBLOX cannot convert between these for obvious reasons. end else for _, baseplate in pairs(workspace.FantasyPlates:GetChildren()) do if baseplate:FindFirstChild("SparkleAtmosphere") then baseplate.SparkleAtmosphere:Destroy() end end end wait(1) end -- between 480 and 1065 is "day"