Page 1 of 1
Functions in a table [SOLVED]
Posted: Mon Aug 21, 2017 9:58 am
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
Re: Functions in a table
Posted: Mon Aug 21, 2017 10:15 am
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.
Re: Functions in a table
Posted: Mon Aug 21, 2017 10:21 am
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.
Re: Functions in a table [SOLVED]
Posted: Mon Aug 21, 2017 1:46 pm
by zorg
Alternatively, if you'd just populate your map table with integer indices, you could then use map[n]() instead, without any concatenating.