How to get/change another script variable?

Hello everyone,
I am new to Defold and trying to learn
How to get/change another script variable??

I have created two objects, a player and stars, with two scripts:
player.script and stars.script.

player.script
local score = 0

stars.script

function on_message(self, message_id, message, sender)
	if message_id == hash("collision_response") then
        local hero_score = go.get_id("hero").score
		hero_score =  hero_score + 10
		go.delete()
	end
end

but not work for me

ERROR:SCRIPT: stars/stars.script:6: attempt to index a userdata value
stack traceback:
  stars/stars.script:6: in function <stars/stars.script:5>

I have tried different combinations, but none of them worked.

local hero_score = go.get_id(“hero”,“score” )
local hero_score = go.get_id("#hero )
local hero_score = go.get_id("/hero )
go.set(“hero”, “score”, +10)

What am I doing wrong? Thank you very much.

You have to use msg.post to post a message to player.script and at player.script you catch that message and do actions

This should help. API reference (msg) (defold.com)

You’ll need to listen for the message on the script that has the variable and then take action.
Use this function to listen for the message:

function on_message(self, message_id, message, sender)

end

This will help explain message passing:
Message passing in Defold

You’ll want to break on the message and study the format of it so you’ll become familiar with it.

@Chung_Xa
@schlista

Thank you for reply
it work fine now

player.script
local score = 0

 function on_message(self, message_id, message, sender)
    	if message_id == hash("add_ten") then
    		score  = score  + 10  -- score  = score  + message.score
    	end
end

stars.script

function on_message(self, message_id, message, sender)
            	if message_id == hash("collision_response") then
            		msg.post("player", "add_ten")
                       msg.post("player", "add_ten", {score = 10})
            		go.delete()
            	end
            end

It’s better to use self.score in your script

1 Like

@Super1234

Since you’re new to Defold. I want to echo what @Chung_Xa said. Definitely take the time to learn what self. is and how it works. It really helps to keep your variables within scope and provides more flexibility the scripts spawns several objects when you use a factor. Self is an amazing feature once I figured it out.