Insert a counter variable inside a IFF statement doesn't work - if-statement

I'm trying to code a script where a counter increment of 1 every time one condition is false, otherwise it's equal to 0.
The condition is a boolean output of the function CROSS().
I've tried:
1° version
var countSma50 = 0
countSma50_=countSma50
iff(cross(open, sma(close, 50)), countSma50=0, countSma50=countSma50_+1)
but when I plot countSma50 I obtain a line adding 1 from the first bar of the chart up to the last, countSma50 never return to 0.
or
2°Version
if cross(close,sma(close, 50))==true
countSma50+=1
else
countSma50=0
but the compiler return to me " Syntax error at input 'countSma50'."
The two script give me errors or wrong counter value..
The goal is to create a counter increasing of 1 at every bar, resetting itself every time the close crosses under/above the single moving average (sma).
Anyone can help me?

The second version was almost there, note that variables declared in the local scope are not visible from the global context of the script, declare the variable in the global scope first and re-assign later, the script below reset the value to 0 if there is a cross() trigger, otherwise will keep counting every bar:
//#version=4
study("My script")
var int countSma50 = 0
if cross(close,sma(close, 50))
countSma50 := 0
else
countSma50 += 1
plot(countSma50)

Related

Multiple conditions are true in If statement (Nefted If)

I have a nested if condition :
If (a > 0)
THEN
Delete from sample_table where id = 123;
IF (b > 0)
dummy = error_insert('x','y','The value of b is greater than 0',0);
commit;
Return;
END IF;
END IF;
So I wanted to check if the variable a has greater than 0 and if so it should delete the value from sample_table and then check if the variable b has greater value than 0 and insert the values as mentioned.
But what it actually does it that checks if a is greater than 0 and directly goes to checking if b is greater than 0. It doesnt perform the delete statement.
I don't see the whole code so all I can do is guessing.
There can be 2 reason why code didn't work as you've expected.
First and the easiest, as mentioned by #littlefoot, there are no lines to delete.
It is easy to check and I believe you've already done that and still wondering why records are still there in the database. So here goes the second guess.
Second, it is the postition of "commit" command in your code. The program you have will commit ONLY if a > 0 and b > 0. So, my guess is in your test case "a" is greater than 0 and "b" is not greater than 0 and commit command can't be reached.

C++ how to reset a counter to 0 when a function is called?

I have a question regarding the reset of a counter back to 0. Below is my function
std::string passorFail(double performanceScore, int threshHold)
{
if (performanceScore > threshHold)
{
pass++; //if the judge socres a pass, 1 is added to the counter
return "pass";
}
else
{
return "fail";
}
}
An int variable called '''int pass = 0;''' is declared globally in the scope as it is required by another function. It's called in a way similar to this (PS it has to be global)
somefunction(pass);
Right now this is how the counter behaves. In total the function passorFail is called 4 times as it loops through a vector, and each time it loops through it increments as it should. So an output is something like this.
count after first pass: 3
count after first pass: 5//increases by 2
count after first pass: 8//increases by 3
count after first pass: 12//increases by 4
What I want to do is display how much the count increments by in each iteration, so something more like this rather than what's displayed above.
count of first pass: 3
count of first pass: 2
count of first pass: 3
count of first pass: 4
I tried setting pass to 0 after I return "pass" in the if statement like the below code, however it still displays the total number of passes rather than how much it increases by in each iteration.
if (performanceScore > threshHold)
{
pass++;
return "pass";
}
Any help would be appreciated :) thankyou
You don't show the code that prints the count, but what you want is a separate variable that keeps track of the value of pass the last time it was printed. So you want something like this:
printf("count of first pass: %d\n", pass - lastpass);
lastpass = pass;

C for loop syntax understanding

I am doing a program for tic-tac-toe and i have a line with
for ( count = 1; count < 10 && winner == 0; count++ );
I referred to other programs and came up with this.
And I'm not very sure of what the entire line means. I have searched up online but I dont understand the meaning of initialization statement ( count = 1 ) and the test expression. And also want to clarify, count++ means increase count right?
Let's have a look at the structure of a for loop:
for ( init-statement; condition; iteration_expression) statement;
From cppreference, a for loop does the following:
Executes init-statement once, then executes statement and iteration_expression repeatedly, until the value of condition becomes false. The test takes place before each iteration.
For your case:
init statement: at the beginning count is initialized to 1
condition: check if count is less than 10 and you don't have a winner yet
iteration_expression: cout++ increases count by 1
statement: you haven't provided that, but it will be executed until the condition is false.
Syntax of for loop is
for(initialization; condition; increment/decrement){
statement;
}
initialization:
Before we start looping, we will initialize the variable to certain value.
In this case, you are initializing 'count' variable to 1
Condition:
In condition part, To stop the loop at certain point you have to provide some conditions.
In this case, condition is 'count<10 && winner==0'. Note that, you are using And(&&) operation so, loop will stop only after both of the conditions are satisfied.
increment/decrement:
Based on the problem, you can choose to increment or decrement the loop variable('count'). In this case, count++ means you are incrementing the count by 1 after each iteration.
for (initialize;condition;increment/decrement)
for loop means
you initialize the variable
you apply a condition to stop the for loop
you execute a single time the loop body (if the condition satisfied)
then you increase or decrease the value of that variable and go to step 2

Lua game development, table seems to delete itself after each interation

What I am trying to do is a little addon which would let me know how much time I have spent casting during combat in %,
function()
local spell, _, _, _, _, endTime = UnitCastingInfo("player")
-- getting information from the game itself whether im "Casting"
local inCombat = UnitAffectingCombat("player")
-- getting information form the game if combat is true (1) or not (nil)
local casting = {}
local sum = 0
if inCombat == 1 then
if spell then
table.insert(casting, 1)
else
table.insert(casting, 0)
end
else
for k in pairs (casting) do
casting [k] = nil
end
end
for i=1, #casting, 1 do
sum = sum + casting[i]
end
return( sum / #casting ) end
-- creating a list which adds 1 every frame I am casting and I am in combat,
-- or adds 0 every frame I'm not casting and I'm not in combat.
-- Then I sum all the numbers and divide it by the number of inputs to figure
-- out how much % I have spent "casting".
-- In case the combat condition is false, delete the list
For some reason these numbers don't add up at all, I only see "1" when both conditions are satisfied, or 0 if the combat condition is satisfied.
There might be some better approach I'm sure, but I am kind of new to lua and programming in general.
You say you're new to Lua, so I will attempt to explain in detail what is wrong and how it can be improved, so brace yourself for a long read.
I assume that your function will be called every frame/step/tick/whateveryouwanttocallit of your game. Since you set sum = 0 and casting = {} at the beginning of the function, this will be done every time the function is called. That's why you always get 0 or 1 in the end.
Upvalues to the rescue!
Lua has this nice thing called lexical scoping. I won't go into much detail, but the basic idea is: If a variable is accessible (in scope) when a function is defined, that function remembers that variable, no matter where it is called. For example:
local foo
do
local var = 10
foo = function() return var end
end
print(bar) -- nil
print(foo()) -- 10
You can also assign a new value to the variable and the next time you call the function, it will still have that new value. For example, here's a simple counter function:
local counter
do
count = 0
counter = function() count = count + 1; return count; end
end
print(counter()) -- 1
print(counter()) -- 2
-- etc.
Applying that to your situation, what are the values that need to persist from one call to the next?
Number of ticks spent in combat
Number of ticks spent casting
Define those two values outside of your function, and increment / read / reset them as needed; it will persist between repeated calls to your function.
Things to keep in mind:
You need to reset those counters when the player is no longer casting and/or in combat, or they will just continue where they left off.
casting doesn't need to be a table. Tables are slow compared to integers, even if you reuse them. If you need to count stuff, a number is more than enough. Just make casting = 0 when not in combat and increase it by 1 when in combat.
Thank you for feedback everyone, in the end after your suggestions and some research my code looks like this and works great:
function()
local spell, _, _, _, startTime, endTime, _, _, _ = UnitCastingInfo("player")
local inCombat = UnitAffectingCombat("player")
local inLockdown = InCombatLockdown()
local _, duration, _, _ = GetSpellCooldown("Fireball")
casting = casting or {}
local sum = 0
if inCombat == 1 or inLockdown == 1 then
if spell or duration ~= 0 then
casting[#casting+1] = 1
elseif spell == nil or duration == 0 then
casting[#casting+1] = 0
end
else
local next = next
local k = next(casting)
while k ~= nil do
casting[k] = nil
k = next(casting, k)
end
end
for i=1, #casting, 1 do
sum = sum + casting[i]
end
return(("%.1f"):format( (sum / #casting)*100 ).. "%%") end
what i noticed is there was a problem with reseting the table in the original code:
for k in pairs (casting) do
casting [k] = nil
it seemed like either some zeros stayed there, or the table size didnt "shrink" i dont know.
Maybe intereger would be faster then a table, but honestly i dont see any performance issues even when the table gets ridicolously big (5 min, 60 fps, thats 18k inputs) also for the sake of learning a new language its better to do it harder way in my opinion
Regards

Am I Missing Something? Changing Dictionary Value

I've been messing around with this code for much longer than necessary. I'm changing to change the value of a dictionary entry depending on a person's choice.
while points <= 10:
print "You have " + str(points) + " points left.\n"
stats = {
"Strength": 0,
"Dexterity": 0,
"Constitution": 0,
"Intelligence": 0,
"Wisdom": 0,
"Charisma": 0
}
for i in sorted(stats):
print i + ": \t" + str(stats[i])
statInc = raw_input("\nWhere do you want to put your points? ").capitalize()
if statInc in stats:
points -= 1
stats[statInc] += 1
I started off with the stats[statInc] as a if/elif that specifies the strings by name. I can't get the values to change, but the point number will decrease accordingly. I know this because I originally had points set to 10.
I've never had this problem before with my other codes that revolved around dictionaries and their values. But I've tried tackling this from every angle and I feel like an idiot.
Nothing is changing because you are setting stats to {"Strength": 0,"Dexterity": 0,"Constitution": 0,"Intelligence": 0,"Wisdom": 0,"Charisma": 0} within your while loop. Every time it loops around, it will recreate stats, making it appear like it never changed.
The way to fix this would be to put the stats = {"Strength": 0,"Dexterity": 0,"Constitution": 0,"Intelligence": 0,"Wisdom": 0,"Charisma": 0} line before you enter your while loop.
You're re-instantiating your dictionary every time the loop evaluates. Move your initial stats declaration out of your loop (before it) so those values aren't reset continuously.
Note that you'll also want to test for while points > 0 instead of points <= 10 since you're starting at 10 and decrementing rather than starting at 0 and incrementing. You could also just test your max points value against sum(stats.values()) to be sure you're getting the current sum rather than using a counter variable, though in this case it doesn't really matter.