This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
ThinkInvisible's profile picture

[Lua] [Question] Is there something like Select Case?

Started by ThinkInvisible, 27 August 2012 - 12:01 PM
ThinkInvisible #1
Posted 27 August 2012 - 02:01 PM
The code
Select Case variable
  case value0
    code
  case value1
    code
  etc.
  case else
    code
in .NET is used to do things based on a variable instead of using lots of if structures. Is there anything like this in Lua?
Lettuce #2
Posted 27 August 2012 - 05:02 PM
I'm… sorry. I don't understand your question. I've never worked with .NET, so I'm unsure what you are going for here. Could you tell me what sort of program you are writing? I'm assuming you mean something like conditional statements, but I (or probably anyone, for that matter) don't know what you need without more detail.
If I can help you, I will. But even if I can't, a bit more description means someone else might.
ThinkInvisible #3
Posted 27 August 2012 - 05:07 PM
This (VB.Net):
Select Case daynumber 'we are testing the variable "daynumber"
  case 0 'is it zero?
	dayname = "Monday" 'do this if so
  case 1 'or is it one?
	dayname = "Tuesday" 'then do this
  case 2 'and so on
	dayname = "Wednesday"
  case 3
	dayname = "Thursday"
  case 4
	dayname = "Friday"
  case 5, 6 'is it five OR six?
	dayname = "Weekend!" 'then do this
  case else 'did all of the above fail?
	print("Error: invalid number.") 'then do these
	dayname = "What?"
end select 'stop testing the variable

is equivalent to this (lua):
if daynumber == 0 then
  dayname = "Monday"
elseif daynumber == 1 then
  dayname = "Tuesday"
elseif daynumber == 2 then
  dayname = "Wednesday"
elseif daynumber == 3 then
  dayname = "Thursday"
elseif daynumber == 4 then
  dayname = "Friday"
elseif daynumber == 5 or daynumber == 6 then
  dayname = "Weekend!"
else
  print("Error: invalid number.")
  dayname = "What?"
end

so it's mostly organization.
Lettuce #4
Posted 27 August 2012 - 06:52 PM
After running several trials to see if I could shorten that, the best I found was to try a table:
Spoiler

name = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}
while true do
    print "What day is it?"
    daynumber = io.read()
    daynumber = tonumber(daynumber)
        if daynumber == 1 then
        print "It is" print(name[1])
        elseif daynumber == 2 then
        print "It is" print(name[2])
        elseif daynumber == 3 then
        print "It is" print(name[3])
        elseif daynumber == 4 then
        print "It is" print(name[4])
        elseif daynumber == 5 then
        print "It is" print(name[5])
        elseif daynumber == 6 or daynumber == 7 then
        print "It's a weekend! Hooray!"
        else
        print "Where do you live?"
        end
end

That looks a bit cleaner.
I should really use tables more often, they are quite useful. For an in-depth guide on them, check the ComputerCraft wiki.
Hope that helps.
– Lettuce
ardera #5
Posted 27 August 2012 - 07:02 PM
I know what you mean, in JAVA there is something like this too, but lua hasn't this feature… I think its added in 5.2 but Im not sure… (CC uses 5.1)
Lettuce #6
Posted 27 August 2012 - 07:16 PM
Found an even better way. Still using tables, shortened last post to 11 lines. Previously it was 21.
Spoiler

name = {"Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
while true do
    print "What day is it?"
    daynumber = io.read()
    daynumber = tonumber(daynumber)
        if daynumber == 0 or daynumber >= 8 then
        print "Where do you live?!"
        else
        print "It is" print(name[daynumber])
        end
end
That's as clean as you're gonna get it in Lua.
kreezxil #7
Posted 21 September 2013 - 11:27 AM
Found an even better way. Still using tables, shortened last post to 11 lines. Previously it was 21.
Spoiler

name = {"Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
while true do
	print "What day is it?"
	daynumber = io.read()
	daynumber = tonumber(daynumber)
	if daynumber == 0 or daynumber >= 8 then
		print "Where do you live?!"
	else
		print "It is" print(name[daynumber])
	end
end
That's as clean as you're gonna get it in Lua.

10 Lines!

name = {"Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
while true do
    print "What day is it?"
    daynumber = tonumber(io.read())
    if daynumber < 1 or daynumber > 7 then
        print "Where do you live?!"
    else
        print "It is" .. name[daynumber]
    end
end

But this is not the same as a SELECT block.
kreezxil #8
Posted 21 September 2013 - 11:35 AM
Sweet holy Jesus found this great article on how to implement SELECT CASE into lua and from what I know I can do with LUA in CC 1.53, this can be done. http://dev.oz-apps.com/?p=265
Kingdaro #9
Posted 21 September 2013 - 11:41 AM
To answer the OP's question, no, there isn't. Either use elseifs, or find another, more efficient way to implement your solution.




name = {"Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
while true do
    print "What day is it?"
    daynumber = tonumber(io.read())
    if daynumber < 1 or daynumber > 7 then
        print "Where do you live?!"
    else
        print "It is" .. name[daynumber] --# this line would error.
    end
end

Dropping parentheses only works if you have a single, solitary literal string.
BigTwisty #10
Posted 21 September 2013 - 11:37 PM
6 lines!

name = {"Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
while true do
    print "What day is it?"
    day = name[tonumber(io.read())]
    print(day and "It is "..day or "Where do you live?!")
end
Dave-ee Jones #11
Posted 22 September 2013 - 03:27 AM
6 lines!

name = {"Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
while true do
	print "What day is it?"
	day = name[tonumber(io.read())]
	print(day and "It is "..day or "Where do you live?!")
end

Lol. Nice try but you have to set the day variable, so it won't ever say "Where do you live?!". Nice try tho.
BigTwisty #12
Posted 22 September 2013 - 08:09 AM
6 lines!

name = {"Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
while true do
	print "What day is it?"
	day = name[tonumber(io.read())]
	print(day and "It is "..day or "Where do you live?!")
end

Lol. Nice try but you have to set the day variable, so it won't ever say "Where do you live?!". Nice try tho.

I do! On line 4, day is either set to the string for the current day or nil if the day number is out of bounds. Try it, it will work.
kreezxil #13
Posted 22 September 2013 - 09:27 AM
– snip –
worthless rewrite removed
– snip –

Also based on that article I linked:
Spoiler

local coffee = 0
local sheet = {}

function Sunday()
	print "Glory to the King!"
end

function Monday()
	print "Oh crap! It's Monday, how many cups of coffee do you want to drink?"
	coffee=tonumber(io.read())
	if coffee > 3 then
	   print "Oh dear! What did you do last night!"
	else
	   print "Have a great day!"
	end
end

function Tuesday()
	print "Aren't you glad you survived Monday!"
	coffee = coffee - 5
end

function Wednesday()
   print "Have you checked the computer craft forums for in any responses to threads you've participated in? .... Hmmm...."
end

function Thursday()
   -- crunch time, gotta finish the spread sheet
  print "With all of this coffee you had all week, hopefully you can input 10 number right quick!"
  for i=1,10 do
	 print "#"
	 sheet[1]=tonumber(io.read())
  end
  print "Great maybe the boss will give you a break, after all tomorrow is Friday!"
end

function Friday()
  -- You are burnt out from the week's work
  -- you can't think of anything to do except
  local planAParty = true
end

function Saturday()
   if planAParty and coffee > 5 then
	  print "Due to the weekly stress you have decided to throw that party after all and invite all of your friends over!"
   else
	  print "It's been a good week and you want to spend the weekend casually alone with friends."
   end
   planAParty = false
end

function defaultFunc()
   print "What planet do you live on?!"
end

local name = { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }

function Select(case)
   func = name[case]
   if func ~= nil then
	  func()
   else
	  defaultFunc()
	  return false
   end
   return true
end

while true do
   print "What day is it? "
   day=io.read()
   local result=select(day)
   if not result then
	  return
   end
end

Considering how hard that is, I think "if then elseif else end" is far simpler, however this probably has its merits too. I am willing to bet one of the pros could easily mod the above to be far more efficient and reusable (generic) than it is now.
Edited on 22 September 2013 - 07:49 AM
Shefla #14
Posted 22 September 2013 - 09:34 AM

name = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
while true do
	print "What day is it?"
	print(name[tonumber(io.read())] and "It is "..day or "Where do you live?!")
end

It seems the day variable in this version is never initialized.

By the way I think using a table to replicate switch / select is good for simple use cases but it miss break / continue statements and also doesn't let cascade program flow to the next case when not calling break.
kreezxil #15
Posted 22 September 2013 - 09:48 AM

name = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
while true do
	print "What day is it?"
	print(name[tonumber(io.read())] and "It is "..day or "Where do you live?!")
end

It seems the day variable in this version is never initialized.

Your're right, I it's total garbage and can't be done the way I wrote it. Day must be captured as a variable before being processed inside the print string.
BigTwisty #16
Posted 22 September 2013 - 11:30 AM

name = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
while true do
	print "What day is it?"
	print(name[tonumber(io.read())] and "It is "..day or "Where do you live?!")
end

It seems the day variable in this version is never initialized.

Your're right, I it's total garbage and can't be done the way I wrote it. Day must be captured as a variable before being processed inside the print string.

Nice try! This approach would work if you didn't have to print "It is " before the day.


name = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
while true do
	print("What day is it?  ", name[tonumber(io.read())] or "Where do you live?!")
end
kreezxil #17
Posted 22 September 2013 - 01:22 PM
What about this at 3 lines!

name = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
function getDay() day=name[tonumber(io.read())] if day ~=nil then print ("It is " .. day) end return day end
while true do print ("What day is it? (1-7) ",getDay() or "Where do you live?!") end
ElvishJerricco #18
Posted 22 September 2013 - 02:21 PM
So I think the underlying point everyone's trying to make here is the same one the creators of Lua believe in: Lua doesn't need select case (or switch case, as it is called in most languages). Lookup tables, functions as values, and if/elseif things are more than enough to do it; possibly more compactly, but definitely in a more Lua-like style.
BigTwisty #19
Posted 22 September 2013 - 06:40 PM
What about this at 3 lines!

name = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
function getDay() day=name[tonumber(io.read())] if day ~=nil then print ("It is " .. day) end return day end
while true do print ("What day is it? (1-7) ",getDay() or "Where do you live?!") end

Now you're just cheating. You're just stringing statements together. If you do that, you might as well just put it all on 1 line. Your code is actually quite a step back with respect to efficiency.

The point was to reduce the number of function calls as far as possible to show how little Lua actually needs select case statements. I think we've proven our point.

(I still think my coded was the smallest, though…)
kreezxil #20
Posted 22 September 2013 - 09:54 PM
I don't see anywhere in this thread where readability was stated as a rule. But I'll give you the point. In fact I thought it was Select Case, did you have any comments on the article I found and my implementation of it?
BigTwisty #21
Posted 22 September 2013 - 11:42 PM
I don't see anywhere in this thread where readability was stated as a rule. But I'll give you the point. In fact I thought it was Select Case, did you have any comments on the article I found and my implementation of it?
I read through it, but it doesn't seem to be as efficient as the simple if then elseif that is typically used in Lua. It's a creative way of using tables, but I don't think it really adds anything useful while requiring more code to do the same thing.