Re: Why is my global variable not visible to my function?

Andriy Rysin <[email protected]>
Newsgroups gmane.comp.lang.groovy.user
Message-ID <CAOZT1o0jYiwzWYrFsLnbpzEmYfAjCL=X4D6Y3sxwkidNacuepw@mail.gmail.com>
The variables at the top are not global (they are local to the script main
function).
You can make them visible to the functions with @Field annotation

Regards
Andriy

On Thu, Aug 10, 2023, 6:30 PM James McMahon <[email protected]> wrote:

> Hello. I am trying to use a variable I define globally in a function that
> follows within my script. Here is my code:
>
> def currentYear = LocalDate.now().getYear()
> def yearValue
> def monthValue
> def dayValue
>
> boolean validateDate(String myYYYY, String myMM, String myDD) {
>
>     // Acceptable range for years is assumed to be 120 years in the past
> to 40 years into the future
>
>     log.error("in validateDate, myYYYY is ${myYYYY}")
>     log.error("in validateDate, myMM is ${myMM}")
>     log.error("in validateDate, myDD is ${myDD}")
>     log.error("in validateDate, currentYear is 2023")
>     log.error("in validateDate, currentYear is ${currentYear}")
>
>     yearValue = Integer.parseInt(myYYYY)
>     monthValue = Integer.parseInt(myMM.replaceFirst(/^0+/, ''))
>     dayValue = Integer.parseInt(myDD.replaceFirst(/^0+/, ''))
>
>
>     //if ((yearValue >= currentYear - 120 && yearValue <= currentYear +
> 40) && \
>     //    (monthValue >= 1 && monthValue <= 12) && \
>     //    (dayValue >= 1 && dayValue <= 31) \
>     //   ) { return true }
>     //   else { return false }
>
>     //log.error("about to validate in validateDate, using
> ${yearValue.toString()} and ${currentYear.toString()}")
>     log.error("about to validate in validateDate, using
> ${yearValue.toString()} and 2023")
>
>     //if ((yearValue >= (currentYear - 120)) && (yearValue <= (currentYear
> + 40))) { return true } else { return false }
>     if ((yearValue >= (2023 - 120)) && (yearValue <= (2023 + 40))) {
> return true } else { return false }
> }
>
> In my log I find the first four log.error() output statements, but I do
> not see the line that I expect:
> in validateDate, currentYear is ${currentYear}
>
> currentYear does not seem to be known to my function validateDate(). What
> ios my error here? How can I correct this?
>
> Thank you in advance for your help.
>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.