Solved Accessing Global Variables within "enclosed scope"

Discussion in 'Plugin Development' started by Xp10d3, Sep 21, 2020.

Thread Status:
Not open for further replies.
  1. Offline

    Xp10d3

    Noob Java question: how would I access a global variable within an "enclosed scope" as my error describes? I know all about scopes, but this kinda stumps me. To be fair, I never learned Java properly and go off my JS and PHP knowledge. I did take a a few lessons on Java and know enough to get my way around Bukkit API. Anyways, if I have this method:
    Code:java
    1.  
    2. public void test() {
    3. int count = 1;
    4. }
    5. [/syntax=java]
    6. And add a Bukkit Runnable, lets say:
    7. [syntax=java]
    8. public void test() {
    9. int count = 1;
    10. new BukkitRunnable() {
    11. @Override
    12. public void run() {
    13. count++
    14. }
    15. }
    16. }
    17. [/syntax=java]
    18. I want to access the variable count inside the runnable, but obviously that isn't possible. Would I access the variable from another class? I don't think that would work since you can't access the core variable that I declared at the top of my class, and I don't want to move the count variable inside the runnable. How would I accomplish this? Sorry for the stupid question.[/syntax]
     
    Last edited: Sep 21, 2020
  2. Offline

    timtower Administrator Administrator Moderator

    @Xp10d3 Move it to the class instead of function.
     
  3. Offline

    Xp10d3

    What do I move? The variable? So:
    Core class:
    Code:java
    1.  
    2. public class Core extends JavaPlugin {
    3. int count = 1;
    4. }
    5.  

    PlayerListeners class:
    Code:java
    1.  
    2. public class PlayerListeners implements Listener {
    3. ...
    4. public void test() {
    5. if (...) {
    6. new BukkitRunnable() {
    7. @Override
    8. public void run() {
    9. private Core core;
    10. core.count = core.count += 1;
    11. }
    12. }.runTaskLater(core, 20);
    13. }
    14. }
    15. }
    16.  

    Is that what you mean?
    ok idk whats going on with the [syntax tags. sorry
     
    Last edited: Sep 21, 2020
  4. Offline

    timtower Administrator Administrator Moderator

    @Xp10d3 You end without the =java part
    And that is an option, do need to make it static though.
    Do note that multiple runnables will increase the speed.
     
  5. Offline

    Xp10d3

    Ah, thanks tim. What do you mean by:
     
  6. Offline

    timtower Administrator Administrator Moderator

    Have 2 runnables on 1 timer and value will change very fast
     
  7. Offline

    Xp10d3

    Ah I see. Thanks!
     
Thread Status:
Not open for further replies.

Share This Page