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

Efficient time value?

Asked by 8 years ago

Hi guys! I am trying to save a "Time" value with Datastore and then compare it to another number when they join the game again.

Basically, it is in the this format Hours:Minutes:Seconds:Milliseconds

However, I have a problem - I can convert this to a number without the ":" and compare it to the new number when they join the game as it is a NumberValue, but to display it to the player, I want to put the ":" back in - what is the easiest way to do it? :) Thanks!

2 answers

Log in to vote
0
Answered by 8 years ago

Two options:

1.

Make individual values for each time segment and change the time with a script.

local hours = script.Hours
local minutes = script.Minutes
-- etc.

2.

Use string manipulation to get the number (value has to be a string). NOTE: The string does not have any ':' in it, they will be added in the script.

local val = script.Time
local hours = string.sub(val.Value,1,2)
local minutes = string.sub(val.Value,3,4)
local seconds = string.sub(val.Value,5,6)
local mseconds = string.sub(val.Value,7,8)

print(hours.. ":" ..minutes.. ":" ..seconds.. ":" ..mseconds)

The only problem is that changing the numbers may be problematic, so you can have another script that changes the time through a similar method with variables:

local hour = 00
local minute = 05
local second = 12
local msecond = 54

script.Time.Value = hour.. "" ..minute.. "" ..second.. "" ..msecond

:) Hope I helped.

0
A much easier alternative is to not try and format their time at all when you save it, and just use a raw integer. You can convert an integer into readable time much more easily than the reverse. adark 5487 — 8y
0
Really? I didn't know that you could do that :P TY TheDeadlyPanther 2460 — 8y
Ad
Log in to vote
0
Answered by 8 years ago

Though TheDeadlyPanther's suggestion is easiest, you can do the following (this is possibly what adark meant) - combining all the components into a single number:

--Saving
time = milliseconds + seconds * 1000 + minutes * 1000 * 60 + hours * 1000 * 60 * 60
--Loading
hours = math.floor(time / (1000 * 60 * 60))
time = time % (1000 * 60 * 60)
minutes = math.floor(time / (1000 * 60))
time = time % (1000 * 60)
seconds = math.floor(time / 1000)
time = time % 1000
milliseconds = time

Another option (which you can combine with the others) is to use the full range of valid datastore characters to encode your number(s). You can use string.char(1) through string.char(128) -- that's 127 possibilities per digit, which is a lot more than the 10 per digit you get by just using numbers! Unfortunately, you need to do complicated math to encode and decode a number to use that 127 possibilities, but it is possible.

Answer this question