Log In  

How can I choose a variable as an argument in a function? Why doesn't this work? And what can I do instead?

timer=1

function updatetimer(i)
    if i<300 then
        i+=1
    else
        i=1
    end
end

function _update()
    updatetimer(timer)
end

function _draw()
    cls()
    ?timer
end
P#118611 2022-10-05 13:17 ( Edited 2022-10-05 13:17)

You'd need to return and assign i from the function in order to do what you want to do here:

timer=1

function updatetimer(i)
    if i<300 then
        i+=1
    else
        i=1
    end

    return i
end

function _update()
    timer=updatetimer(timer)
end

function _draw()
    cls()
    ?timer
end
P#118612 2022-10-05 13:21

@2bitchuck Thank you!

P#118614 2022-10-05 13:37

So 2bitchuck has already given you the answer to get this working but in case you're not familiar it's worth knowing the difference between what's called passing by value and passing by reference.

Lua passes simple values—like numbers and strings—by value. Which basically means that it makes a copy of the data and passes that in instead of passing the original data itself. The function receives the same value but not the same object. That's why your version of the code wasn't working: timer and i are different objects so changing i doesn't affect timer.

Tables/Arrays, on the other hand, are passed by reference. Essentially passing by reference means you're passing in the actual object itself. (This isn't technically true, I'm glossing over some details but it's close enough for this explanation.) Since you're passing the actual object, any changes you make to it inside a function will persist outside of the function. For instance, this works without having to return a value:

timer={t=1}

function updatetimer(i)
    if i.t<300 then
        i.t+=1
    else
        i.t=1
    end
end

function _update()
    updatetimer(timer)
end

function _draw()
    cls()
    ?timer.t
end

This isn't a good solution to your actual problem—go with what 2bitchuck has given you—but it's worth knowing about because it can sometimes lead to bugs if you pass something to a function and change it without meaning to then can't figure out why some table property has the wrong value.

P#118617 2022-10-05 15:16

@jasondelaat Thank you! I wouldn't have known that otherwise!

P#118634 2022-10-05 19:00

[Please log in to post a comment]