Why is my script not working?

  1. What do you want to achieve? Keep it simple and clear!

create a function that subtracts variables

  1. What is the issue? Include screenshots / videos if possible!

the variable does not change

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!

local var = 100 -- create variable
print(var) -- print variable
subtract = function(var) -- create function subtract
	var = var - 1
end
subtract(var) -- call function subtract
print(var) -- print new var

Expected: 99

Result: 100

You are keeping the variable name as the same variable name you’re using for your function. Tested this, and this works.

local var = 100
print(var)
rest = function(var1)
	var = var1 - 1
end
rest(var)
print(var)
1 Like

not working

code:

local myvar = 100

print(myvar)

rest = function(var)

var = var - 1

end

rest(myvar)

print(myvar)

Expected: 99

Result: 100

Change the first “var” in the function to “myvar”

1 Like

You’re providing the function a number. What the function sees is

rest = function(var) --100

var = var - 1 --It sees: 100 = 100 - 1 (Not possible.)

Which is why you need it to do

rest = function(var) --100

myvar = var - 1 --It sees ThisVariable = 100 - 1 (Possible)

when you reference var inside the function, it’s changing the var sent as an argument. To properly achieve what you’re doing you could do:

local var = 100 -- create variable
print(var) -- print variable
subtract = function(var) -- create function subtract
	return var - 1
end
var = subtract(var) -- call function subtract
print(var) -- print new var

or simply:

local var = 100
print(var) --100
var -= 1
print(var) --99
1 Like