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

Rename variable contents

Started by shournk, 16 May 2014 - 02:08 AM
shournk #1
Posted 16 May 2014 - 04:08 AM
How do I change the contents of a variable according to a predetermined set? I.e. I have a variable Args that can be set to "monday" or "tuesday", but if it's monday I want it to instead contain "1" and for tuesday "2". I've been using ifs and elses.
gezepi #2
Posted 16 May 2014 - 06:49 AM
A table might work for you. Something like this:

local days = {
  monday=1,
  tuesday=2,
  wednesday=3
  --etc...
}
Then to convert "monday" into 1 just do

local dayOfWeek = days["monday"]
shournk #3
Posted 16 May 2014 - 01:26 PM
A table might work for you. Something like this:

local days = {
  monday=1,
  tuesday=2,
  wednesday=3
  --etc...
}
Then to convert "monday" into 1 just do

local dayOfWeek = days["monday"]

With my example, could I do something like

arg = day[arg]
To change the variable contents to it's table counterpart?
gezepi #4
Posted 16 May 2014 - 08:09 PM
Yep, the new value of arg would become the number from the table. I would suggest adding code to make sure that it actually got a value out though. If you try to get a value from a table that isn't there (no index) then the value is nil. An easy way to do this is:

print("Type the day of the week:")
local input = read()
--Convert the string to all lowercase, it's easier to deal with
arg = string.tolower(input)
arg = days[arg]
if arg then
  --The day was successfully translated
  --Do stuff
else
  --The input was not found in the table
  error(input.."not found in table!")
end

The if statement is checking whether arg is any value besides nil or false. So if arg is 1 then it evaluates as true, same as if it was 2 or 3 or "hello" or a table or anything, it could be anything except false or nil.