Jump to content
  • 0

Is there a better way of writing menu/submenus?


PMT_Ives

Question

local function mem1()
   print("menu 1")
end

local function mem2()
   print("menu 2")
end

-- Is there a better way to write this?
-- I mostly don't wanna use elseif each time I add a string on line 11 (gg.choice({'A', 'B', 'C', 'D'})
local choice = gg.choice({'A', 'B', 'C', 'D'})
if (choice == 1) then
    mem1()
elseif (choice == 2) then
    mem2()
end	

Is there a better way to write this? It's a hassle always changing the number in the "elseif" statement every time I add a string, something to make this automatic would be nice.

Link to comment
Share on other sites

4 answers to this question

Recommended Posts

Take a look at the approach shown in this post: 

How to create Menu with values (#2j8mdsbl)

The idea is to have one table with definition of every item in a menu with each item having a name and a function. It is then trivial to construct a table of names and functions from the main table. Table with names is then passed to "gg.choice" or "gg.multiChoice" function and the returned value(s) is used to index functions table to retrieve the function that corresponds to selected feature(s) and finally retrieved function is called.

Link to comment
Share on other sites

31 minutes ago, CmP said:

Take a look at the approach shown in this post: 

How to create Menu with values (#2j8mdsbl)

The idea is to have one table with definition of every item in a menu with each item having a name and a function. It is then trivial to construct a table of names and functions from the main table. Table with names is then passed to "gg.choice" or "gg.multiChoice" function and the returned value(s) is used to index functions table to retrieve the function that corresponds to selected feature(s) and finally retrieved function is called.

Can't seem to figure it out, any help?

Link to comment
Share on other sites

1 hour ago, PMT_Ives said:

Can't seem to figure it out, any help?

There is a code in that post, but in case you have difficulties with adapting it, here is a basic template: 

local function f1()
  print("Feature 1")
end

local function f2()
  print("Feature 2")
end

local features = {
  {name = "First feature", func = f1},
  {name = "Second feature", func = f2}
}

local featureNames = {}
local featureFunctions = {}
for i, v in ipairs(features) do
  table.insert(featureNames, v.name)
  table.insert(featureFunctions, v.func)
end

local choice = gg.choice(featureNames)
if choice ~= nil then
  featureFunctions[choice]()
end
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.