Functions in a table [SOLVED]

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
User avatar
akopyl
Prole
Posts: 21
Joined: Fri Jun 27, 2014 1:20 pm

Functions in a table [SOLVED]

Post by akopyl »

Is there a more elegant way of doing this?

Code: Select all

function map.setLvl(n)
  if n == 0 then
    map.load0()
  elseif n == 1 then
    map.load1()
  elseif n == 2 then
    map.load2()
  elseif n == 3 then
    map.load3()
  end
end
This doesn't work

Code: Select all

function map.setLvl(n)
 map.load[n]()
end
Last edited by akopyl on Mon Aug 21, 2017 10:21 am, edited 1 time in total.
User avatar
zorg
Party member
Posts: 3441
Joined: Thu Dec 13, 2012 2:55 pm
Location: Absurdistan, Hungary
Contact:

Re: Functions in a table

Post by zorg »

Yes, there is!

Code: Select all

function map.setLvl(n)
 map['load' .. n]()
end
You need to use the [] notation for tables, and concatenate the first part of the key with the index, then call that value which is the function returned by that expression.
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.
User avatar
akopyl
Prole
Posts: 21
Joined: Fri Jun 27, 2014 1:20 pm

Re: Functions in a table

Post by akopyl »

zorg wrote: Mon Aug 21, 2017 10:15 am Yes, there is!

Code: Select all

function map.setLvl(n)
 map['load' .. n]()
end
You need to use the [] notation for tables, and concatenate the first part of the key with the index, then call that value which is the function returned by that expression.
Wow, crazy.
Thanks for the help. I always knew there was a better way than doing my dumbass if stack.
User avatar
zorg
Party member
Posts: 3441
Joined: Thu Dec 13, 2012 2:55 pm
Location: Absurdistan, Hungary
Contact:

Re: Functions in a table [SOLVED]

Post by zorg »

Alternatively, if you'd just populate your map table with integer indices, you could then use map[n]() instead, without any concatenating.
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.
Post Reply

Who is online

Users browsing this forum: srg and 25 guests