Function that switch values in a table

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
jefolo
Prole
Posts: 12
Joined: Wed Dec 23, 2020 3:20 pm

Function that switch values in a table

Post 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
User avatar
zorg
Party member
Posts: 3090
Joined: Thu Dec 13, 2012 2:55 pm
Location: Absurdistan, Hungary
Contact:

Re: Function that switch values in a table

Post 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.
Me and my stuff :3True Neutral Aspirant. Why, yes, i do indeed enjoy sarcastically correcting others when they make the most blatant of spelling mistakes. No bullying or trolling the innocent tho.
jefolo
Prole
Posts: 12
Joined: Wed Dec 23, 2020 3:20 pm

Re: Function that switch values in a table

Post 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
Post Reply

Who is online

Users browsing this forum: No registered users and 16 guests