I am currently working on modifying an existing function, by Ray, that checks the time elapsed and remaining:
Here is the function:
function ago(date){
var interval = "";
var offset = 0;
var result = 0;
if (isDate(arguments.date)){
var formattedDate = dateFormat(arguments.date, "dddd dd mmmm yyyy");
var k = datediff('d',arguments.date,now());
//writedump(k);
//abort;
if(k contains '-') {
if (dateDiff("s", now(), arguments.date) < 60){
// less than 1 minute show interval in seconds
offset = dateDiff("s", now(),arguments.date);
interval= offset == 1 ? "second":"seconds";
result = "#offset# #interval# left";
}else if (dateDiff("n",now(),arguments.date) < 60){
// less than 1 hour show interval in minutes
offset = dateDiff("n", now(),arguments.date);
interval= offset == 1 ? "minute":"minutes";
result = "#offset# #interval# left";
}else if (dateDiff("h",now(),arguments.date) < 24){
// less than 24 hours display interval in hours
offset = dateDiff("h", now(), arguments.date);
interval = offset == 1 ? "hour":"hours";
result = "#offset# #interval# left";
}else if (dateDiff("d",now(),arguments.date) < 2){
// less than 2 days display yesterday
result = "Tommarrow";
}else if (dateDiff("d", now(), arguments.date) < 7){
// less than 7 days display day
result = dayOfWeekAsString( dayOfWeek( arguments.date ));
}else if (dateDiff("w", now(), arguments.date)){
offset = dateDiff("w",now(), arguments.date);
interval = offset == 1 ? "week":"weeks";
result = "#offset# #interval# left";
}else if (dateDiff("m", now(), arguments.date)){
offset = dateDiff("m",now(), arguments.date);
interval = offset == 1 ? "month":"months";
result = "#offset# #interval# left";
}else if (dateDiff("yyyy", now(), arguments.date)){
offset = dateDiff("yyyy", now(), arguments.date);
interval = offset == 1 ? "year":"years";
result = "#offset# #interval# left";
}
else{
// otherwise display date
result = formattedDate;
}
}
else {
if (dateDiff("s", arguments.date, now()) < 60){
// less than 1 minute show interval in seconds
offset = dateDiff("s", arguments.date, now());
interval= offset == 1 ? "second":"seconds";
result = "#offset# #interval# ago";
}else if (dateDiff("n", arguments.date, now()) < 60){
// less than 1 hour show interval in minutes
offset = dateDiff("n", arguments.date, now());
interval= offset == 1 ? "minute":"minutes";
result = "#offset# #interval# ago";
}else if (dateDiff("h", arguments.date, now()) < 24){
// less than 24 hours display interval in hours
offset = dateDiff("h", arguments.date, now());
interval = offset == 1 ? "hour":"hours";
result = "#offset# #interval# ago";
}else if (dateDiff("d", arguments.date, now()) < 2){
// less than 2 days display yesterday
result = "yesterday";
}else if (dateDiff("d", arguments.date, now()) < 7){
// less than 7 days display day
result = dayOfWeekAsString( dayOfWeek( arguments.date ));
}else if (dateDiff("w", arguments.date, now())){
offset = dateDiff("w", arguments.date, now());
interval = offset == 1 ? "week":"weeks";
result = "#offset# #interval# ago";
}else if (dateDiff("m", arguments.date, now())){
offset = dateDiff("m", arguments.date, now());
interval = offset == 1 ? "month":"months";
result = "#offset# #interval# ago";
}else if (dateDiff("yyyy", arguments.date, now())){
offset = dateDiff("yyyy", arguments.date, now());
interval = offset == 1 ? "year":"years";
result = "#offset# #interval# ago";
}
else{
// otherwise display date
result = formattedDate;
}
}
interval = "<abbr title='" & formattedDate & "'>" & result & "</abbr>";
}
return interval;
}
The result is "1 week left" or "2 weeks ago". But rather than "2 weeks", it should show me "1 week 4 days", or whatever the days remaining are, unless it is exactly "2 weeks".
Wow that is a lot of if statements, probably better to look for a calculated approach like the following:
<cfset date1 = CreateDate(2014,07,07)>
<cfset date2 = CreateDate(2014,07,19)>
<cfset dateDifference = dateDiff("d",date1,date2)>
<cfset weeks = int(dateDifference/7)>
<cfset days = dateDifference MOD 7>
<cfoutput>
#weeks# weeks and #days# days ago
</cfoutput>
Then if you need to do it the other way around, e.g. weeks and days until, you can to that as well, just change the output text. All you need to do is make sure that date1 is always before (in time) than date2.
UPDATE
After looking at this again and based on what your where looking for I found this blog post from Steve Withington:
http://www.stephenwithington.com/blog/index.cfm/2008/8/15/Using-ColdFusion-to-Create-an-Ebayesque-Auction-Countdown-Timer-Custom-Tag
I then took his code and turned it into a function that I think should do what you want, or pretty close to it:
<cfscript>
function timeUntil(dateStart, dateEnd) {
var compareGivenDates = DateCompare(arguments.dateStart, arguments.dateEnd, "s");
var rightNow = DateFormat(now(), "mm/dd/yyyy") & " " & TimeFormat(now(), "hh:mm:ss tt");
var compareNow = DateCompare(rightNow, arguments.dateStart, "s");
switch (compareNow) {
case -1:
throw(message="End date must be after start date", detail="The end date must be after the start date otherwise the calculations will not be possible.");
case 1:
var arguments.dateStart = rightNow;
}
var returnTimeRemaining="";
var dateStart = DateFormat(arguments.dateStart, "mm/dd/yyyy") & " " & TimeFormat(arguments.dateStart, "hh:mm:ss tt");
var dateEnd = DateFormat(arguments.dateEnd, "mm/dd/yyyy") & " " & TimeFormat(arguments.dateEnd, "hh:mm:ss tt");
var hdif = Abs(DateDiff("h", dateEnd, dateStart));
var ndif = Abs(DateDiff("n", dateEnd, dateStart));
var sdif = Abs(DateDiff("s", dateEnd, dateStart));
var years2go = Abs(DateDiff("yyyy", dateEnd, dateStart));
var months2go = Abs(DateDiff("m", dateEnd, dateStart));
var weeks2go = Abs(DateDiff("ww", dateEnd, dateStart));
var days2go = Abs(DateDiff("d", dateEnd, dateStart));
if (DatePart('h', now()) LT 12 OR days2go EQ 1) {
var h = 'h';
} else {
var h = 'H';
}
var hours2go = TimeFormat(dateEnd-dateStart, h);
var min2go = TimeFormat("#dateEnd-dateStart#", "m");
var sec2go = TimeFormat("#dateEnd-dateStart#", "s");
var newmonths = months2go-(years2go*12);
var tempDate = dateadd("m", months2go, arguments.dateStart);
var newweeks = Abs(DateDiff("ww", arguments.dateEnd, tempDate));
var tempdays = Abs(DateDiff("d", arguments.dateEnd, tempDate));
var newdays = tempdays-(newweeks*7);
var comparison = DateCompare(dateStart, dateEnd, "s");
switch (comparison) {
case -1:
if (years2go GTE 1) {
returnTimeRemaining = returnTimeRemaining & "#years2go#y ";
}
if (newmonths GTE 1) {
returnTimeRemaining = returnTimeRemaining & "#newmonths#m ";
}
if (newweeks GTE 1) {
returnTimeRemaining = returnTimeRemaining & "#newweeks#w ";
}
if (newdays GTE 1) {
returnTimeRemaining = returnTimeRemaining & "#newdays#d ";
}
if (ndif GTE 60) {
returnTimeRemaining = returnTimeRemaining & "#hours2go#h ";
}
if (sdif GTE 60) {
returnTimeRemaining = returnTimeRemaining & "#min2go#m ";
}
if (sdif GTE 1) {
returnTimeRemaining = returnTimeRemaining & "#sec2go#s";
} else {
returnTimeRemaining = "0s";
}
break;
case 0:
returnTimeRemaining = false;
break;
case 1:
returnTimeRemaining = false;
break;
}
return returnTimeRemaining
}
</cfscript>
<cfoutput>
#timeUntil(CreateDateTime(2013, 7, 19, 0, 0, 0), now())#
</cfoutput>
Apart from converting it to script and making it a function, there are a few changes in here from Steve's original to get it to not return the months, weeks, days, etc... when they are 0. I've run a load of test dates through it and it appears to work ok for all the cases I have tried. Still feel there is far more code there then should be necessary but I don't have the time to spend refactoring it down.
UPDATE 2
Used this code in a programming hack session today and refactored it and improved it to the following:
<cfscript>
public string function timeDifferenceFormattedString(
required date dateStart,
date dateEnd = Now()
) {
// Is datestart actually after dateend?
switch (DateCompare(arguments.dateStart,arguments.dateEnd)) {
case 1:
var suffix = 'since';
var currentLowerDate = arguments.dateEnd;
var currentUpperDate = arguments.dateStart;
break;
case 0:
return 'The dates are the same';
break;
case -1:
var suffix = 'until';
var currentLowerDate = arguments.dateStart;
var currentUpperDate = arguments.dateEnd;
break;
}
var arrDateParts = [ 'yyyy' , 'm' , 'ww' , 'd', 'h', 'n', 's' ];
var arrDatePartsHuman = [ 'year' , 'month' , 'week' , 'day', 'hour', 'minute', 'second' ];
var arrDateDiffs = [];
for ( var i = 1; i<=ArrayLen(arrDateParts);i++ ) {
var thisDiff = Int(DateDiff( arrDateParts[i] , currentLowerDate, currentUpperDate ));
if (
thisDiff > 0
) {
arrDateDiffs.add( thisDiff & ' ' & arrDatePartsHuman[i] & ( thisDiff > 1 ? 's' : '' ) );
currentLowerDate = DateAdd( arrDateParts[i] , thisDiff, currentLowerDate );
}
}
arrDateDiffs.add(suffix);
return ArrayToList(arrDateDiffs,' ');
}
</cfscript>
<cfoutput>
<p>#timeDifferenceFormattedString(CreateDateTime(2013, 7, 10, 0, 0, 0), now())#</p>
<p>#timeDifferenceFormattedString(CreateDateTime(2013, 7, 10, 0, 0, 0), CreateDateTime(2013, 7, 10, 0, 0, 0))#</p>
<p>#timeDifferenceFormattedString(now(),CreateDateTime(2013, 7, 10, 0, 0, 0))#</p>
</cfoutput>
To take this further again you could pass in the "human" output values and suffixes as well to make the string formatting even more flexible.
Related
I am a beginner trying to write a simple piece of code for backtesting between 2 dates, using variables, to check bullish condition on a daily candle (Day0) for every day, if its met I want to check bullish condition on next daily candle (Day1) (storing the closing values for stoploss later on) and if true then use the high of the 3rd daily candle (Day2) as my entry strategy. Exit will be on 30th day from entry or at stoploss. Request help in fixing the code below:
strategy("Bullish scanner", overlay=true)
start = timestamp (2022,1,1,0,0)
end = timestamp (2022,9,30,0,0)
Day0 = dayofweek(start)
If Day0 >= start and Day0 <= end
Bull = (close(day0) > 1.1 * open(Day0))
var Day0Close = security(syminfo.tickerid, 'D', close(day0))
var Day1 = Day0 + 1
Trigger = (close(Day1) > open(Day1)) and (close(Day1) > close(Day0))
plotshape(Bull, style=shape.arrowup, location=location.abovebar, color=color.green, text='Bullish')
plotshape(Trigger, style=shape.arrowup, location=location.abovebar, color=color.yellow, text=’Trigger’)
var Day1Close = security(syminfo.tickerid, 'D', close(Day1))
var Day2 = Day1 + 1
var Day2High = security(syminfo.tickerid, 'D', high(Day2))
strategy.entry("Long", strategy.long, 1, Day2High, when = Trigger)
var stoploss = 0.9 * Day0Close
var NextDay = Day2 + 1
var NextDayClose = security(syminfo.tickerid, 'D', close(NextDay))
var count = 0
for count = 0 to 30
if NextDayClose > stoploss
NextDay = NextDay + 1
var NextDayClose = security(syminfo.tickerid, 'D', close(NextDay))
var count = count + 1
else NextDayClose = stoploss
strategy.close("Long", NextDayClose)
Code doesnot compile
I have a button that submits information and that works. All the numbers will be positive when entered by clients. The question at hand is:
If A4 = "Sell", cells A16, A18, and A20, return those numbers as negative values instead of positive. If A4 = "Buy", then return as is (positive).
Here's what I currently have. I don't know where to input this IF statement, or even how.
function SubmitBuy() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formS = ss.getSheetByName("Front Sheet"); //Data entry sheet
var dataS = ss.getSheetByName("Front Sheet"); //Data Sheet
var values = [[formS.getRange("A2").getValue(),
formS.getRange("A4").getValue(),
formS.getRange("A6").getValue(),
formS.getRange("A8").getValue(),
formS.getRange("A10").getValue(),
formS.getRange("A12").getValue(),
formS.getRange("A16").getValue(),
formS.getRange("A18").getValue(),
formS.getRange("A20").getValue(),
formS.getRange("A28").getValue(), ]];
dataS.getRange(dataS.getLastRow() +1, 3, 1, 10 ).setValues(values);
ClearCells();
}
Get all of Column A's values and manipulate them using Array.map and Set:
function SubmitBuy() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const frontSheet = ss.getSheetByName('Front Sheet'); //Data entry sheet
const valuesA1A28 = frontSheet.getRange('A1:A28').getValues();
const rowsNeeded = [2, 4, 5, 8, 10, 12, 16, 18, 20];
const criteriaRow = 4;
const rowsToModify = new Set([16, 18, 20]);
const valuesNeeded = [
rowsNeeded.map((thisRow) => {
const thisValue = valuesA1A28[thisRow - 1][0];
if (
rowsToModify.has(thisRow) &&
valuesA1A28[criteriaRow - 1][0] === 'Sell'
)
return -thisValue;
else return thisValue;
}),
];
frontSheet
.getRange(frontSheet.getLastRow() + 1, 3, 1, 10)
.setValues(valuesNeeded);
ClearCells();
}
Need help. I have my whole code here. I am trying to compare the touched object(text) to the value of a local variable answer, but it always prints nil value of text. How can I compare those two?
function scene:create( event )
local sceneGroup = self.view
local temp1 = math.random(0,10)
local temp2 = math.random(0,10)
local answer = temp1 + temp2
local background = display.newImage( "bg0.png" )
background.x = display.contentWidth*0.5
background.y = display.contentHeight*0.5
local text2 = display.newText(temp1,90,45,"Arial",55)
text2:setFillColor(0, 0, 0)
local plus = display.newText(" + ",140,45,"Arial",55)
plus:setFillColor(0, 0, 0)
local text3 = display.newText(temp2,180,45,"Arial",55)
text3:setFillColor(0, 0, 0)
local equals = display.newText(" = ",235,45,"Arial",55)
equals:setFillColor(0, 0, 0)
local secondsLeft = 02 * 60
local clockText = display.newText("02:00", 270, -7, "Arial", 35)
clockText:setFillColor(0,0,0)
local function updateTime()
secondsLeft = secondsLeft - 1
local minutes = math.floor(secondsLeft / 60)
local seconds = secondsLeft % 60
local timeDisplay = string.format("%02d:%02d", minutes, seconds)
clockText.text = timeDisplay
if timeDisplay == "00:00" then
GameOver()
print "Game Over!!!"
end
end
local countDowntimer = timer.performWithDelay(1000,updateTime,secondsLeft)
local function offscreen(self, event)
if(self.y == nil) then
return
end
if(self.y > display.contentHeight - 100) then
Runtime:removeEventListener("enterFrame", self)
self:removeSelf()
end
end
local function balloonTouched(event)
if (event.phase == "began") then
print( "object touched =", event.target )
print (answer)
if event.target == answer then
print "Good"
local temp1 = math.random(0,10)
local temp2 = math.random(0,10)
local text2 = display.newText(temp1,90,45,"Arial",55)
text2:setFillColor(0, 0, 0)
local text3 = display.newText(temp2,180,45,"Arial",55)
text3:setFillColor(0, 0, 0)
secondsLeft = secondsLeft + 5
else
print "Wrong Answer"
secondsLeft = secondsLeft - 3
end
Runtime:removeEventListener("enterFrame", event.self)
event.target:removeSelf()
end
return true
end
local function ulit()
lobo = { ("blue.png"), ("green.png"), ("red.png"), ("orange.png"), ("pink.png"), ("violet.png"), ("yellow.png") }
local lobo = display.newImage( lobo[math.random(7)], math.random(35,260), 600 )
physics.addBody( lobo, { density=0.1, friction=2.0, bounce=0.0, velocity=-40, isSensor=true } );
lobo.gravityScale = -0.1111111115
sceneGroup:insert( lobo )
lobo.enterFrame = offscreen
local text = display.newText(math.random(0,9),50,30,"Arial",40)
text.id = "sagot"
sceneGroup:insert( text )
text.enterFrame = offscreen
function lobo:enterFrame()
text.x, text.y = lobo.x, lobo.y;
end
Runtime:addEventListener( "enterFrame", lobo)
lobo:addEventListener("touch", balloonTouched)
end
timer.performWithDelay(300,ulit,0)
local backBtn = widget.newButton
{
labelColor = { default={255}, over={128} },
defaultFile= "home.png",
overFile= "home.png",
width=50, height=50,
onRelease = onBackBtnRelease
}
backBtn.x = 20
backBtn.y = -7
sceneGroup:insert( background )
sceneGroup:insert( clockText )
sceneGroup:insert( backBtn )
sceneGroup:insert( text2 )
sceneGroup:insert( plus )
sceneGroup:insert( text3 )
sceneGroup:insert( equals )
end
Try (should work)
local function ulit()
local mRandom = math.random
local imagesNames = { "blue.png", "green.png", "red.png", "orange.png", "pink.png", "violet.png", "yellow.png" }
local lobo = display.newImage( imagesNames[mRandom(7)], mRandom(35,260), 600 )
...
local n = mRandom(0, 9)
local text = display.newText(n,50,30,"Arial",40)
lobo.number = n
...
local function balloonTouched(event)
...
-- here event.target is equal lobo
if event.target.number == answer then
...
In ulit function you use the same name (lobo) for table object and diplay object. That is wrong.
My problem at the moment is I am trying to change a label(label 16) to the first value of entry_values[0] which isn't working I have tried passing it in as a variable and many other things, after about an hour of research I couldn't find a solution.I think the main problem is that it sets the label before the code with the entry is run so that it wont change. when I set it to a textvariable it produces an empty string (I think) but when I use just text it puts in a 0 where I expect my number.
def sub_menu(root):
global subpage
subpage = Frame(root)
button5 = Button(subpage, text="Save Generation Data",
command = lambda: save_entries())
button5.grid(row = 1, column = 6, sticky = E)
button6 = Button(subpage, text="Return To Main Page",
command = lambda: switch_page("main"))
button6.grid(row = 0, column = 6, sticky = W)
juveniles_label0 = Label(subpage,text="Juveniles")
adults_label1 = Label(subpage,text="Adults")
seniles_label2 = Label(subpage,text="Seniles")
population_label3 = Label(subpage,text="Population (Thousands)")
survival_rate_label4 = Label(subpage,text="Survival Rate (Between 0 and 1)")
birth_rate_label5 = Label(subpage,text="Birth Rate")
number_of_gens_label6 = Label(subpage,text="Number of Generations")
disease_trigger_label7 = Label(subpage,text="Disease Trigger Point")
global entry0
entry0 = Entry(subpage)
global entry1
entry1 = Entry(subpage)
global entry2
entry2 = Entry(subpage)
global entry3
entry3 = Entry(subpage)
global entry4
entry4 = Entry(subpage)
global entry5
entry5 = Entry(subpage)
global entry6
entry6 = Entry(subpage)
global entry7
entry7 = Entry(subpage)
global entry8
entry8 = Entry(subpage)
juveniles_label0.grid(row = 0, column = 1)
adults_label1.grid(row = 0, column = 2)
seniles_label2.grid(row = 0, column = 3)
population_label3.grid(row = 1, column = 0)
survival_rate_label4.grid(row = 2, column = 0)
birth_rate_label5.grid(row = 3, column = 0)
number_of_gens_label6.grid(row = 3, column = 2)
disease_trigger_label7.grid(row = 4, column = 0)
entry0.grid(row = 1, column = 1)
entry1.grid(row = 1, column = 2)
entry2.grid(row = 1, column = 3)
entry3.grid(row = 2, column = 1)
entry4.grid(row = 2, column = 2)
entry5.grid(row = 2, column = 3)
entry6.grid(row = 3, column = 1)
entry7.grid(row = 3, column = 3)
entry8.grid(row = 4, column = 1)
return subpage
def save_entries(): #entry recieve point
save_page = Frame(root)
""" if e0 < 0:
make a check to check if value is < 0 dont accept and if a value is inputed or not using if type(string_name) == str """
e0 = entry0.get()
if e0 >= 0:
entry_values[0] = (e0)
e1 = entry1.get()
if e0 >= 0:
entry_values[1] = (e1)
e2 = entry2.get()
if e0 >= 0:
entry_values[2] = (e2)
e3 = entry3.get()
if e0 >= 0:
entry_values[3] = (e3)
e4 = entry4.get()
if e0 >= 0:
entry_values[4] = (e4)
e5 = entry5.get()
if e0 >= 0:
entry_values[5] = (e5)
e6 = entry6.get()
if e0 >= 0:
entry_values[6] = (e6)
e7 = entry7.get()
if e0 >= 0:
entry_values[7] = (e7)
e8 = entry8.get()
if e0 >= 0:
entry_values[8] = (e8)
print entry_values
return save_page
def display_values(root):
sub2 = Frame(root)
global entry_values
label8 = Label(sub2, text = "Juveniles")
label9 = Label(sub2, text = "Adults")
label10 = Label(sub2, text = "Seniles")
label11 = Label(sub2, text = "Population(Thousands)")
label12 = Label(sub2, text = "Survival Rate(Between 1 and 0)")
label13 = Label(sub2, text = "Birth Rate")
label14 = Label(sub2, text = "Number of Generations")
label15 = Label(sub2, text = "Disase Trigger Point")
label16 = Label(sub2, text = entry_values[0])
label17 = Label(sub2, textvariable = entry_values[1])
label18 = Label(sub2, textvariable = "")
label19 = Label(sub2, textvariable = "")
label20 = Label(sub2, textvariable = "")
label21 = Label(sub2, textvariable = "")
label22 = Label(sub2, textvariable = "")
label23 = Label(sub2, textvariable = "")
label24 = Label(sub2, textvariable = "")
button7 = Button(sub2, text="Return To Main Page",
command = lambda: switch_page("main"))
label8.grid(row = 0, column = 1)
label9.grid(row = 0, column = 2)
label10.grid(row = 0, column = 3)
label11.grid(row = 1, column = 0)
label12.grid(row = 2, column = 0)
label13.grid(row = 3, column = 0)
label14.grid(row = 3, column = 3)
label15.grid(row = 4, column = 0)
label16.grid(row = 1, column = 1)
label17.grid(row = 1, column = 2)
label18.grid(row = 1, column = 3)
label19.grid(row = 2, column = 1)
label20.grid(row = 2, column = 2)
label21.grid(row = 2, column = 3)
label22.grid(row = 3, column = 1)
label23.grid(row = 3, column = 3)
label24.grid(row = 4, column = 1)
button7.grid(row = 0, column = 0)
return sub2
In order to change the text of a label you can do:
label["text"] = textVar
or
label.config(text=textVar)
So in your above code, when the entry changes, reconfigure the label using one of the above options.
Each time the arithmetic question is generated and whenever i pick the right or wrong answer the statement of function checkanswer() always goes on if-statement "Correct". How am i able to create if/else statement correctly base on an arithmetic question varanswer = var1 + var2
function checkAnswer(event)
if(#theAnswer == questionGen()) then
instructionsText.text = "Correct!";
instructionsText:toFront()
generateBalls()
for i=1, allBallsGroup.numChildren do
display.remove(allBallsGroup[1])
end
else
instructionsText.text = "Incorrect!";
instructionsText:toFront()
generateBalls()
for i=1, allBallsGroup.numChildren do
display.remove(allBallsGroup[1])
end
end
end
function questionGen()
local questionVar1 = display.newImage("ygSquare.png", 150, 500);
local var1 = math.random(1,9)
local var1Display =display.newText(var1, 200, 500, native.systemFont, 200)
questionVar1.width = 200
questionVar1.height = 200
questionVar1.x = 350
questionVar1.y = 500
var1Display.x = 350
var1Display.y = 500
var1Display:setTextColor("#000000")
local questionVar2 = display.newImage("blueSquare.png", 150, 500);
local var2 = math.random(1,9)
local var2Display = display.newText(var2, 200, 500, native.systemFont, 200)
questionVar2.width = 200
questionVar2.height = 200
questionVar2.x = 700
questionVar2.y = 500
var2Display.x = 700
var2Display.y = 500
var2Display:setTextColor("#000000")
local operator = " + "
local operatorDisplay = display.newText(operator, 400, 500, native.systemFont, 200)
operatorDisplay:setTextColor("#000000")
local varAnswer = var1 + var2
return varAnswer
end
Your random values are greater than 1 and adding two numbers greater than 1, will be greater than 1. This means that questionGen() is always returning true. I would divide var1 and var2 by 9 so that it is normalized. Also you will need to add a line to check if varAnswer say greater than 1 (0.5+05) return true else return false.
function questionGen()
local varAnswer = var1/9 + var2/9
if(varAnswer>=1) then return true end
return false
end
Now in your other function you can check if(questionGen()) then
This is use to create inputs or choices in my game macro
local theAnswer= "";
local theAnswerText;
function createBall()
local var numberArray = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "11", "12", "13", "14", "15", "16", "17", "18"};
local tens = {questionGen(#theAnswer)}
local ballType = math.random(8);
local ballSize = math.random(2)
local letterIndex
local letter
if(createTens == true) then
letterIndex = math.random(#tens)
letter = tens[letterIndex];
else
letterIndex = math.random(#numberArray);
letter = numberArray[letterIndex];
letterIndex = math.random(#tens)
letter = tens[letterIndex];
end
local ballGroup = display.newGroup();
local ball
local ballRadius
if(ballType == 1) then
ball = display.newImage("whiteBall.png");
elseif(ballType == 2) then
ball = display.newImage("brownBall.png");
elseif(ballType == 3) then
ball = display.newImage("pinkBall.png");
elseif(ballType == 4) then
ball = display.newImage("whiteBall.png");
elseif(ballType == 5) then
ball = display.newImage("yellowBall.png");
elseif(ballType == 6) then
ball = display.newImage("whiteBall.png");
elseif(ballType == 7) then
ball = display.newImage("greenBall.png");
else
ball = display.newImage("redBall.png");
end
if(ballSize == 1)then
ball.width = 200;
ball.height = 200;
ballRadius = 30;
else
ball.width = 200;
ball.height = 200;
ballRadius = 30;
end
local letterText = display.newText( letter, 0,0, native.systemFontBold, 100 );
letterText:setTextColor(0,0, 0);
letterText.x = ball.x;
letterText.y = ball.y;
ballGroup:insert(ball);
ballGroup:insert(letterText);
ballGroup.x = math.random(ballRadius,display.contentWidth-ballRadius*3);
ballGroup.y= 40;
physics.addBody(ballGroup, 'dynamic',{friction = 0,bounce = 0,radius = ballRadius*3});
ballGroup.name = "ball";
ballGroup.letter = letter;
ballGroup:addEventListener('tap',checkAnswer);
table.insert(allBalls,ballGroup)
allBallsGroup:insert(ballGroup)
end