What is the problem with my math operation?

Note: If you know a better title for the question, that would help me a lot too.

Honestly, I’m not quite sure if I’m forming this question correctly, but…

--Upgrade_const
damage_upgrade = 1
speed_upgrade = 1
hp_upgrade = 1
	

function init(self)
(some code)
end

function on_message(self, message_id, message, sender)
	--Upgrade_message
	if message_id == hash("speed_upgrade") then
		speed_upgrade = 10 
	end

And I get an error like this: ERROR:SCRIPT: main/main.script:74: attempt to perform arithmetic on global ‘speed_upgrade’ (a userdata value)

If I change the code a little bit:

	if message_id == hash("speed_upgrade") then
		speed_upgrade = 10
	end

Then I get this error after the first use of a GUI element (i.e. first click goes fine, second click gives an error): bad argument #1 to ‘pick_node’ (NodeProxy expected, got number)
stack traceback

My Gui code (I use a separate GUI for the main interface and a separate one for the upgrade menu):

function init(self)
	msg.post(".", "acquire_input_focus")
	
	--GUI_Node
	speed_upgrade = gui.get_node("speed_upgrade")
end

function on_input(self, action_id, action)

	if action_id == hash("touch") and action.pressed then
		if gui.pick_node(speed_upgrade, action.x, action.y) then
			print("test")
			msg.post("main#main", "speed_upgrade")
		end
	end
end

Important: If I do this, the program does not give any error, so I think the problem is in the mathematical operation.

	if message_id == hash("speed_upgrade") then
		print("Hello world")
	end

Addendum: This code also refuses to run.

speed_upgrade = speed_upgrade + 1

You are falling into a classic Lua beginners trap. Lua variables are global by default, which means a global variable is accessible from all scripts. In your case you first assign a number to speed_upgrade and then a gui node after which you are trying to add 1 to the gui node. This will obviously not work.

In order to make a variable non-global you can either make it a local variable by using the local keyword, or in your case it would make more sense to store the speed_upgrade variable on self.

function init(self)
   self.damage_upgrade = 1
   self.speed_upgrade = 1
   self.hp_upgrade = 1
   (some code)
end

function on_message(self, message_id, message, sender)
	--Upgrade_message
	if message_id == hash("speed_upgrade") then
		self.speed_upgrade = 10 
	end

Self explained: Writing game logic in scripts
Lua lexcical scoping (local vs global): Lua programming in Defold

3 Likes

Thank you very much ! It turns out that all this time I misunderstood the meaning of global variable in Lua and interpreted it as “global within one script”.

1 Like