Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the alternative for switch statement in Lua language?

I have this piece of code in C++ and i want to know how can i write some codes that replace switch statement in Lua because i face many problems and i need to use this statement.

   int choice;
do// loop
{
      cout<<"\n >>> The General Menu <<< \n";
      cout << endl;
    cout<< " press (1) to Add    "<<endl;
    cout<< " press (2) to Save   "<<endl;
    cout<< " press (3) to Quit " << endl;
    cout<< endl;
      cout<< "Enter your choice please (1/2/3): ";
    cin>>choice;

    switch(choice)
    {
        case 1: 
            add();
            break;
        case 2:
            save();
            break;

        default:
            cout<<" The program has been terminated "<<endl;
           cout<<" Thank you! \n";          
    }   
} while (choice != 3);

} The statement has been used inside a do..while loop.

like image 918
zanaM Avatar asked May 25 '16 21:05

zanaM


3 Answers

In general, if you want a switch statement in Lua, what you ought to be doing is building a table. For your simple case of choice that could be 1, 2, or fail, a simple if statement with a few conditions is sufficient. For more complex cases, a table of functions should be employed:

local c_tbl =
{
  [1] = add,
  [2] = save,
}

local func = c_tbl[choice]
if(func) then
  func()
else
  print " The program has been terminated."
  print " Thank you!";
end

You can use lexical scoping to allow the functions in the table to be able to access local variables, just as if the code was written inline.

like image 163
Nicol Bolas Avatar answered Oct 14 '22 08:10

Nicol Bolas


Try this one (click here to run the script in a Lua compiler), Hope the code is self-explanatory ;-) and

resembles the same pseudo code format..!!

print("enter your choice : ")
mychoice = io.read()

switch = function (choice)
  -- accepts both number as well as string
  choice = choice and tonumber(choice) or choice     -- returns a number if the choic is a number or string. 

  -- Define your cases
  case =
   {
     [1] = function ( )                              -- case 1 : 
             print("your choice is Number 1 ")       -- code block
     end,                                            -- break statement

     add = function ( )                              -- case 'add' : 
             print("your choice is string add ")     -- code block
     end,                                            -- break statement

    ['+'] = function ( )                             -- case '+' : 
             print("your choice is char + ")         -- code block
     end,                                            -- break statement

     default = function ( )                          -- default case
             print(" your choice is din't match any of those specified cases")   
     end,                                            -- u cant exclude end hear :-P
   }

  -- execution section
  if case[choice] then
     case[choice]()
  else
     case["default"]()
  end

end
-- Now you can use it as a regular function. Tadaaa..!!
switch(mychoice)
like image 21
codenio Avatar answered Oct 14 '22 08:10

codenio


While simply creating a table indexed by cases with functions as elements is most probably the fastest approach, there is this solution I've made which IMO has better code readability:

function switch(element)
  local Table = {
    ["Value"] = element,
    ["DefaultFunction"] = nil,
    ["Functions"] = {}
  }
  
  Table.case = function(testElement, callback)
    Table.Functions[testElement] = callback
    return Table
  end
  
  Table.default = function(callback)
    Table.DefaultFunction = callback
    return Table
  end
  
  Table.process = function()
    local Case = Table.Functions[Table.Value]
    if Case then
      Case()
    elseif Table.DefaultFunction then
      Table.DefaultFunction()
    end
  end
  
  return Table
end

Example Use:

switch(Player:GetName())
  .case("Kate", function() print("This player's name rhymes with Fate")end)
  .case("Tod", function() print("This player's name rhymes with Cod") end)
  .default(function() print("This player's name is not Kate or Tod") end)
  .process()
like image 22
Krystilize Avatar answered Oct 14 '22 08:10

Krystilize