Page 1 of 1

Function that switch values in a table

Posted: Wed Dec 30, 2020 10:42 pm
by jefolo
Hello again,
I'm continuing my beginner attemps. I'm trying to write a function that switch values in a table.
I wrote the following funcition: it works if I enter in it directly the variables, but it doesn't if i try to pass the variables as parameters.
Can somebody help me where i'm wrong?

Thank you

Code: Select all

test = {"normal", "text", "imae"}
testselected = 1

function love.draw()
    love.graphics.print(test[testselected])
end

function love.mousepressed( x, y, button, istouch, presses )
  if button==1  then
    test = switchTableParameter(test, testselected)
  end
end

function switchTableParameter(param, selectedparameter)
  for i = 1, #param do
    selectedparameter = selectedparameter + 1
    if selectedparameter > #param then
      selectedparameter = 1
    end
    return param
  end
end

Re: Function that switch values in a table

Posted: Thu Dec 31, 2020 3:39 am
by zorg
test[testselected] is equivalent to test[1] because testselected is equal to 1 initially.
I'm assuming your switchTableParameter function would change testselected to the next value that's in range of the table's numeric indices (in this case, test contains 3 elements, so the param would be 1, 2 or 3.)

Lua does not pass number parameters by reference, so selectedparameter being modified will not do anything to whatever you put there in your function call, in other words, testselected won't be modified)

One way to do this would be to return the value of selectedparameter instead, and store that in testselected... even if that's also overcomplicating things.

Re: Function that switch values in a table

Posted: Thu Dec 31, 2020 1:16 pm
by jefolo
Thank you for the tip, I've modified the code according it and now it works as i had in mind.

Thanks!

Code: Select all

function switchTableParameter(param, selectedparameter)
  selectedparameter = selectedparameter + 1
    if selectedparameter > #param then
      selectedparameter = 1
    end
  return selectedparameter
end