Why doesn't this work

I’m trying to make my programs more effiecent by using more tables and functions.

function setup()
    fin = 1
end
function count(x)
    x = x + 1
    print(x)
end
function draw()
count(fin)
end

I want to make a function that counts up. (So it would go 1,2,3,etc) but it will just print fin+1 and keep that value

it doesn’t work because the x that the count function receives is just a copy of fin, not fin itself.

The easiest way to correct this is

--(1) no need to pass fin to the function
function count()  
   fin=fin+1
end

--or, 
--(2) if you want to use count with other variables as well
function count(x)
    x=x+1
    print(x)
    return x  --pass the value back
end

--and then in draw, you use count like this
fin=count(fin)

Ooh, so i was just making two pointers to the same value. Thanks @ignatz

@Progrmr235 - yes, you can think of numbers and strings as not having pointers at all, so they are always copied, whereas anything else (vec, table, image, …) is passed by pointer

Actually what I don’t understand is how is this

function setup()
x = 0
end
function count(x)
x = x + 1
print(x)
return x
end
function draw()
x = count(x)
end

more efficient then this

function setup()
x = 0
end
function draw()
x = x + 1
print(x)
end

the second one is easier to write and does the same thing.

who says one is more efficient than the other (not me) ?

Never said you said that @ignatz. I just assumed there’s an advantage to using functions you define because it’s more to write. I just can’t see what the advantage is.

No, the advantage of functions is that they

  • avoid duplicating code that gets used more than once,
  • makes your code easier to debug and test (because each function can be tested separately) and
  • make your code neater, eg
--this code....
function draw()
   --100 lines of code doing all sorts of things
end

--is much easier to read like this, with the code split into functions
function draw()
    SetupScreen()
    MovePlayer()
    MoveNPCs()
    ShowStats()
end

@Progrmr235 - with respect to the last example you posted, the first case definitely won’t be more efficient as you’ve got the memory overhead of the extra function and the setup / teardown time of the function call as well (granted it’s minuscule but all these little parts can build up over time) .

In this case, the function is there more to demonstrate the concept.
In practice you’d more likely take the approach suggested by @Ignatz - especially with respect to not duplicating code and also for organising code into logical sections.

Hope this helps
:slight_smile: