In the line boxneeded = boxneeded + 1, the = sign is called the “assignment operator.” It’s like giving a new value to a variable. In this case, it’s saying “take the current value of boxneeded, add 1 to it, and then make that the new value of boxneeded.”
Sorry, I don’t quite understand what your goal or problem is right now. I believe the problem is the variable not changing? or at least you think so, but it does.
The provided code should work, keep in mind elseif has to be spelled together.
What you are basically doing is take the boxneeded or crateneeded value, append it by 1, and then assign it to itself. Which should work.
For example, if boxneeded was 3, it would do boxneeded = 3 + 1.
The variable only evaluates when a mathematical operation or some other operation that involves its value is being performed.
When you created this table, whats being stored inside is a copy of the value from the variable. defining a variable from an element also just gets a copy of it.
In order to assign a new value to this element you must not do this
but instead specify that it is the value inside the list that you wish to change.
This is the correct solution:
local boxneeded = 0
local crateneeded = 0
local needed = {boxneeded,crateneeded}
local chosen = math.random(1,#needed)
needed[chosen] = needed[chosen] + 1
--Or instead you can do this
needed[chosen] += 1
I am assuming that you wish that one of either values be added 1 right?
The problem is that when you do this:
local choose = needed[math.random(1,#needed)]
choose just becomes a copy of the value within the table.
so in this case, this happens:
local choose = 0
local ran = math.random(1,#needed)
choose = needed[ran] --choose becomes a copy of needed[ran]
choose = choose + 1
print(choose) --this prints 1
print(needed[ran]) --this prints 0
--choose ~= needed[ran] because choose is a copy
so the proper way to do this is like this:
local ran = math.random(1,#needed)
needed[ran] = needed[ran] + 1 --the value from within the table will be changed
print(needed[ran]) --prints 1
local needed = {boxneeded,crateneeded} makes copies of the two variables, not references local choose = needed[math.random(1,#needed)] makes a copy of the copy in the table
If you want to increment the variable you can either do
local boxneeded = 0
local crateneeded = 0
if math.random(1,2) == 1 then
boxneeded += 1
else
crateneeded += 1
end
or this:
local needed = {
boxneeded = 0,
crateneeded = 0
}
local choose = math.random(1,#needed)
needed[choose] += 1