Why isn't the code running. It isn't doing anything inside my loop. | Roblox Studio - roblox

None of it's working. Can you please help. This is in Roblox Studio.
local Time = math.floor (game.Lighting:GetMinutesAfterMidnight(480/60))
local intakeAlert = game.StarterGui.Main.IntakeAlert
local prisonerCount = game.ReplicatedStorage.NumPrisoners
local intake = game.ReplicatedStorage.PrisonerIntake -- This is the prisoner intake status
while wait() do
if Time == 8 then -- Checks if it is 8 hours after midnight.
print("Prison Bus Arriving.")
intakeAlert.Visible = true
wait(2)
intakeAlert.Visible = false
end
end

After reading your code, the reason I can say that the reason it is not running is because of this line of code:
if Time == 8 then -- Checks if it is 8 hours after midnight.
The main reason is probably your time variable.
local Time = math.floor (game.Lighting:GetMinutesAfterMidnight(480/60))
First things first, GetMinutesAfterMidnight() doesn't take any parameters. I'm not sure why there is one
Second, you setup your variable at runtime, meaning its value is static. If the ingame time at runtime was 2, then the time variable would remain 2 until the script is stopped.
Here is my fix to this:
local intakeAlert = game.StarterGui.Main.IntakeAlert
local prisonerCount = game.ReplicatedStorage.NumPrisoners
local intake = game.ReplicatedStorage.PrisonerIntake -- This is the prisoner intake status
local debounce -- Make sure this event doesn't fire several times
while true do
local currentTime = math.floor(game.Lighting.ClockTime) -- You can change this to GetMinutesBeforeMidnight if you want. Might have to do some math.
if currentTime == 8 then -- Checks if it is 8 hours after midnight.
if debounce then return end -- Return if the event has already been fired.
debounce = true
print("Prison Bus Arriving.")
intakeAlert.Visible = true
wait(2)
intakeAlert.Visible = false
else
debounce = false -- If its 9 after midnight, debounce will be set to false for the next day.
end
wait() -- You should avoid using this, I suggest changing it to something like RunService.Heartbeat:Wait() but that's your choice.
end

Related

IF statement not detecting numbers

My if statement is not working, in other words it's not wanting to detect player scores. I've also tried checking if it exists.
Here is the whole script:
local price = script.Parent.Price.Value
local item = script.Parent.Price.Value
local db = true
local function buy(player)
local itemName = game.ServerStorage.GravityCoil:Clone()
print("got to click detecting")
if player:FindFirstChild("leaderstats").Tix.Value >= 5 then
print("checked price")
db = false
player.leaderstats.Tix.Value = player.leaderstats.Tix.Value - price
itemName.Parent = player.Backpack
print("gave item")
wait(.10)
db = true
end
end
script.Parent.ClickDetector.MouseClick:Connect(buy)
But we need to focus on one part,
if player:FindFirstChild("leaderstats").Tix.Value >= 5 then
print("checked price")
db = false
player.leaderstats.Tix.Value = player.leaderstats.Tix.Value - price
itemName.Parent = player.Backpack
print("gave item")
wait(.10)
db = true
There are no errors, warnings, anything in the console. I can't pinpoint the problem, I've joined discord servers, I've looked at roblox forums, I just can't find a solution to this problem! So please, if you have 30 minutes just to look at this and try to post an answer, I will praise you. Have a great day.
I suggest removing the FindFirstChild as leaderstats should already exist in player so there is no need to check for it. Also check if your greater sign is correct as you could have meant to put a lesser sign which resulted in the if statement not working.

Turn GUI on and off depending on if player is in region

I have a script working for a rounds based game. It starts with a lobby and an intermission timer of 30 seconds. Then teleports players into a chosen map within a region I defined. During the round it counts down and either ends the round after 180 seconds or if 1 player is left. Players who are killed (or remain at the end of the 180 seconds) are teleported back to the lobby and the cycle continues. I used the script below and it works well. I would like to leverage the table / array from this script to identify players who are in the region and turn off / make invisible a Spectate GUI that I would like to make visible only to players in the lobby (ie. NOT in the region I defined that encompasses the various round maps). But I'm having trouble figuring out how to amend this script. Any help would be greatly appreciated! thanks. CODE below:
'''
while true do -- repeats forever and calls the functions
wait(2)
intermissionTimer()
chooseMap()
loadMap()
wait(2)
teleportPlayers()
wait(2)
local time = roundLength
while wait(1) do
partsInRegion = workspace:FindPartsInRegion3(region, game.ServerStorage.Maps,3000) -- this returns a table
playersFound = {} -- table players found
for i, part in pairs (partsInRegion) do
if part.Parent:FindFirstChild("Humanoid") ~= nil then
playersFound[part.Parent.Name] = part.Parent -- add players character to table
winner = playersFound[part.Parent.Name].Name
print (winner)
print (i, part) -- 0
end
end
function Length(playersFound)
local counter = 0
for _, v in pairs(playersFound) do
counter =counter + 1
end
return counter
end
if time == 0 then
Status.Value = "Round over!"
workspace.SoundLibrary.Nowinner:Play()
break
elseif Length(playersFound)== 1 then
workspace.SoundLibrary.Winner:Play()
Status.Value = winner.. " wins!"
wait(5)
break
else
Status.Value = time .." seconds left"
time = time - 1
end
end
wait (2)
teleportBack()
deleteMap()
end
'''
At the end of your for-loop, you have a table full of players who are still in the game. You can get a list of all of the players in the game by using the Players service. Each player object is stored as a child there, and you can compare the names of your surviving players against the names of all the players to find who is dead.
local partsInRegion = workspace:FindPartsInRegion3(region, game.ServerStorage.Maps,3000)
local playersFound = {}
-- find all the players still alive
for k, part in pairs(partsInRegion) do
if part.Parent:FindFirstChild("Humanoid") ~= nil then
playersFound[part.Parent.Name] = part.Parent
end
end
-- figure out who is dead
local allPlayers = game.Players:GetChildren()
for i, player in ipairs(allPlayers) do
-- if they are not still in the game, they must be dead
if playersFound[player.Name] == nil then
-- get the Spectate gui, replace this line with your actual gui
local gui = ReplicatedStorage.SpectateGui:Clone()
-- give the dead player the spectate gui, if they don't already have it
if player.PlayerGui[gui.Name] == nil then
gui.Parent = player.PlayerGui
end
end
end

Pine scripting: how to find the price X days ago

In Pine Script, how do I find the price based on a certain number of days ago? I've tried something like this...
// Find the price 90 days ago
target = time - 90 * 60 * 60 * 24 * 1000
valuewhen(time < target, close, 1)
...however time < target never seems to return true – presumably because the current bar's time cannot also be in the past at the same time. Perhaps valuewhen() wasn't designed to be used with dynamic values that change on every bar?
Do I need to use a loop instead, and scan through every past bar until I find the date I'm looking for?
Perhaps there's a better way, but the workaround I'm using currently using is a function with a for loop, scanning backwards until the appropriate date is found. Here is my function:
priceXDaysAgo(numDays) =>
targetTimestamp = time - numDays*60*60*24*1000
// Declare a result variable with a "void" value
float result = if false
1
// We'll scan backwards through the preceding bars to find the first bar
// earlier than X days ago (it might be a little greater than X days if
// there was a break in trading: weekend, public holiday, etc.)
for i = 1 to 1000
if time[i] < targetTimestamp
result := close[i]
break
result
You can then call the function anywhere in your script:
priceXDaysAgo(90)

Cron timer testing with psuedo clock in Drools Fusion?

I am trying to test the firing of a rule based on a cron timer using the pseudo clock in Drools Fusion 5.5. I want the rule to fire everyday at 1am:
rule "CALCULATING DATE FOR NEXT DAY"
timer (cron:00 00 01 * * ?)
no-loop
when
$summary: FxSummary(sameDayCcyFlag == false)
then
BusinessDayUtil b = new BusinessDayUtil();
modify($summary) {
setSettlementDate(b);
}
end
I then do the following in my test case:
PseudoClockScheduler timeService = ( PseudoClockScheduler ) ksession.getSessionClock();
DateFormat df = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSZ" );
Date date = df.parse( "2014-01-16T01:00:00.000-0000" );
Summary sum = new Summary("YEN").setSameDayCcyFlag(false);
ksession.fireAllRules();
timeService.advanceTime( date.getTime(), TimeUnit.MILLISECONDS );
ksession.fireAllRules();
It doesn't seem to do anything...no indication that the timer fired or anything. I've also tried to insert a date at say 12:59:50 and advanced the clock 10sec. Also, fireUntilHalt to have the engine running, etc. Nothing seems to work. Am I using this correctly? Does the pseudo clock work with timers? Also, does it fire "missed" timers if I advance the clock past a timer that was supposed to fire?
Think about how cron can be implemented. The basic function is timer, and this works like ye olde kitchen's egg-timer: at one point in time you wind it up, and then it'll ring 4 or 5 minutes later. Thus, for the next cron ring of the bell, the Cook will have to look at the clock and calculate the interval to the indicated point in time.
You'll have to let the Cook look at the clock some time before the next 1:00am, say, around midnight. The code goes something like this, with advance() overloaded with Date and long to advance the pseudo-clock:
date = df.parse( "2014-01-15T00:00:00.000-0000" ); // Note: midnight
advance( date );
kSession.fireAllRules(); // (Ah, ring in one hour!)
advance( 1000*60*60 );
kSession.fireAllRules(); // Ring!
advance( 24*1000*60*60 );
kSession.fireAllRules(); // Ring!
The postman only rings twice ;-)

Using fixedRate timer in MATLAB with different data for each interval (trying to replace for loop with timer)

Is there a way to have a MATLAB timer pass different data on each subsequent call to the timer function? My goal is to cycle through intervals at a fixed rate, and the pause function inside a loop is not precise enough.
I have workng MATLAB code that uses a for loop to send data via serial ports, then wait a specified time before the next iteration of the loop. The serial communication varies in speed, so if I specify 300 seconds as the period, the loop actually executes every 340-360 seconds. Here is the existing code:
clear all;
testFile = input('What is the name of the test data file (with extension): ', 's');
measurementData = csvread(testFile);
intervalDuration = input('What is the measurement change period (seconds): ');
intervalNumber = size(measurementData,2);
% Set up the COM PORT communication
sensorComPort = [101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120];
controllerComPort = [121,122,123,124];
for j=1:intervalNumber
tic
fprintf('\nInterval # %2d\n',rem(j,24));
sensorMeasurementPS = [measurementData(1,j),measurementData(2,j),measurementData(3,j),measurementData(4,j),measurementData(5,j), measurementData(6,j),measurementData(7,j),measurementData(8,j),measurementData(9,j),measurementData(10,j), measurementData(11,j),measurementData(12,j),measurementData(13,j),measurementData(14,j),measurementData(15,j), measurementData(16,j),measurementData(17,j),measurementData(18,j),measurementData(19,j),measurementData(20,j)];
serialSensorObj = startsensorPSWithoutReset(sensorComPort, sensorMeasurementPS);
serialSensorObj = changeMeasurement(serialSensorObj, sensorMeasurementPS);
rc = stopsensorPS(serialSensorObj);
controllerMeasurementPS = [measurementData(21,j),measurementData(22,j),measurementData(23,j),measurementData(24,j)];
serialControllerObj = startControllerPSWithoutReset(controllerComPort, controllerMeasurementPS);
serialControllerObj = changeMeasurement(serialControllerObj, controllerMeasurementPS);
rc2 = stopControllerPS(serialControllerObj);
pause(intervalDuration);
t = toc;
fprintf('Elapsed time = %3.4f\n',t);
end
clear serialSensorObj;
clear serialControllerObj;
The serial functions are specified in other files and they are working as intended.
What I need to do is have the serial communication execute on a more precise 5-minute interval. (The actual timing of the commands inside the interval will still vary slightly, but the commands will kick off every 5 minutes over the course of 24 hours. The current version loses time and gets out of sync with another system that is reading the measurements I'm setting by serial port.)
My first thought is to use a MATLAB timer with the fixedRate execution mode, which queues the function at fixed intervals. However, it doesn't appear that I can send the timer function different data for each interval. I thought about having the timer function change a counter in the workspace, similar to j in my existing for loop, but I know that having functions interact with the workspace is not recommended.
Here's what I've come up with so far for the timer method:
function [nextJ] = changeMeasurement_fcn(obj,event,j,sensorComPort,controllerComPort)
tic
fprintf('\nInterval # %2d\n',rem(j,24));
sensorMeasurementPS = [measurementData(1,j),measurementData(2,j),measurementData(3,j),measurementData(4,j),measurementData(5,j), measurementData(6,j),measurementData(7,j),measurementData(8,j),measurementData(9,j),measurementData(10,j), measurementData(11,j),measurementData(12,j),measurementData(13,j),measurementData(14,j),measurementData(15,j), measurementData(16,j),measurementData(17,j),measurementData(18,j),measurementData(19,j),measurementData(20,j)];
serialSensorObj = startSensorPSWithoutReset(sensorComPort, sensorMeasurementPS);
serialSensorObj = changeMeasurement(serialSensorObj, sensorMeasurementPS);
rc = stopSensorPS(serialSensorObj);
controllerMeasurementPS = [measurementData(21,j),measurementData(22,j),measurementData(23,j),measurementData(24,j)];
serialControllerObj = startControllerPSWithoutReset(controllerComPort, controllerMeasurementPS);
serialControllerObj = changeMeasurement(serialControllerObj, controllerMeasurementPS);
rc2 = stopControllerPS(serialControllerObj);
t2 = toc;
fprintf('Elapsed time = %3.4f\n',t2);
and this is how I would call it from the main m file:
t = timer('TimerFcn',#changeMeasurement,'ExecutionMode','fixedRate','period',intervalDuration);
% then I need some code to accept the returned nextJ from the timer function
This feels a bit sloppy so I'm hoping there's a built-in way to have a timer cycle through a data set.
Another idea I had was to keep the for loop but change the pause function to use a value calculated based on how much time would add up to 5 minutes for the iteration.
To summarize my question:
a) Can I have a timer pass different data to the timer function on each iteration?
b) Is that a good way to go about cycling through the intervals in my data on a precise 5-minute interval?
Thanks!
I stumbled on this page: http://www.mathworks.com/company/newsletters/articles/tips-and-tricks-simplifying-measurement-and-timer-callbacks-with-nested-functions-new-online-support-features.html
and learned that timer callback functions can be nested inside other functions (but not regular scripts).
Using that information, I cut my scenario to the basics and came up with this code:
function timerTestMain_fcn
testFile = input('What is the name of the test data file (with extension): ', 's');
testData = csvread(testFile);
intervalDuration = input('What is the voltage change period (seconds): ');
intervalNumber = size(testData,2);
t = timer('ExecutionMode','fixedRate','period',intervalDuration,'TasksToExecute',intervalNumber);
t.TimerFcn = {#timerTest_fcn};
start(t);
wait(t);
delete(t);
function timerTest_fcn(obj,event)
tic
event_time = datestr(event.Data.time);
interval_id = t.TasksExecuted;
data_value = testData(1,interval_id);
txt1 = 'Interval ';
txt2 = num2str(interval_id);
txt3 = ' occurred at ';
txt4 = ' with data value of ';
txt5 = num2str(data_value);
msg = [txt1 txt2 txt3 event_time txt4 txt5];
disp(msg)
t2 = toc;
fprintf('Elapsed time = %3.4f\n',t2);
end
end
The test data file it requests must be a csv containing a row vector. For example, you could put the values 11,12,13,14,15 across the first row of the csv. The output message would then say 'Interval 1 occurred at [time] with data value of 11', 'Interval 2 occurred at [time] with data value of 12', etc.
The key is that by nesting the functions, the timer callback can reference both the test data and the timer attributes contained in the outer function. The TasksExecuted property of the timer serves as the counter.
Thanks to anyone who thought about my question. Comments welcome.