Discord
Login
Community
DARK THEME

Changing global variables from inside an object

Trying to change a global variable from inside an object does not work. Here, the variable glob does not change by the object call. Seems to me as though it should be changed by the mygame.update() call?

init=function()
  glob="starting text"
  print("glob starting value is "+ glob)
  mygame.update()
  print("glob changed value is "+ glob)
end

mygame=object
  var1=100
  update=function()
    glob="changed"
    var1=999
  end
end

When calling a function of an object like this mygame.update(), the function update will operate in the object's scope. When setting glob to some value, it will create a glob property to the object.

If you want to access (write) a global variable from within an object method, you can address them through the global object like this:

mygame=object
  var1=100
  update=function()
    global.glob="changed"
    var1=999
  end
end

Ah, thanks for that @giles. This was an earlier head-scratcher while I was developing microFarm. I did wonder why variables outside of an object were not changing.

Might be worth updating the online documentation, which says:

the variables are global by default. To define a local variable, use the keyword "local".

Yes this certainly needs to be clarified in the doc!

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community