Created
July 3, 2020 01:47
-
-
Save RadGH/f0367595cc97257c93eb1d913cab3048 to your computer and use it in GitHub Desktop.
Stormworks Lua Microcontroller: Rate of Change
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--[[ | |
Microcontroller Name: Rate of Change | |
Description: Take an input value and outputs the rate of change per second. | |
Inputs: | |
1) Value (number, required): Input number (eg, fuel tank capacity) | |
2) Refresh Rate (number, optional, default 60): Game ticks between each update | |
Outputs: | |
1) Number: Change since last update | |
]]-- | |
-- inputs | |
amount = 0 -- total value amount to monitor change of | |
rate = 60 -- how often to update in ticks (60 = 1 second) | |
-- internal data | |
lastAmount = 0 -- storage for previous samples | |
outAmount = 0 -- result to output | |
initialized = false -- set to true on first run | |
counter = 0 -- increase by 1 per tick, compared against rate | |
function onTick() | |
amount = input.getNumber(1) | |
-- one-time-setup | |
if ( initialized == false ) then | |
initialized = true | |
lastAmount = amount | |
if ( round(input.getNumber(2)) > 0 ) then rate = round(input.getNumber(2)) end | |
end | |
-- do updates at a defined rate | |
counter = counter + 1 | |
if ( counter > rate ) then | |
-- calculate the new output | |
outAmount = amount - lastAmount | |
-- capture the current amount in memory | |
lastAmount = amount | |
-- restart the counter | |
counter = 0 | |
end | |
-- always output a value, the value doesn't necessarily change each tick | |
output.setNumber( 1, outAmount ) | |
end | |
function onDraw() | |
end | |
function round( a ) | |
return math.floor(a + 0.5) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment