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

Way to check if variable includes string?

Started by ebernerd, 20 December 2014 - 01:29 AM
ebernerd #1
Posted 20 December 2014 - 02:29 AM
Hey there, Computercraft users!
I'm writing an API that would make stuff so much easier. I'd love to make a simplified background and text function. Currently, it's like this:


function bg(color)
  term.setTextColor(color)
end

function txt(color)
  term.setTextColor(color)
end

Now, is there a way to say "if color includes the string blah". I'd like to do this so that, I could do both:

--M is the api.

m.txt(yellow)

--OR

m.txt(colors.yellow)

Not sure if I'm explaining it well. Basically it detects if the "colors." is included in the argument. If it is, then go along. If it isn't, run the function as if it was there.

Catching my drift?

Hope you can help! Thanks so much!
theoriginalbit #2
Posted 20 December 2014 - 02:40 AM
if you're wanting to support colours in both the colors.x variables, as well as strings such as "yellow" I have made a function for this in the past for ccConfig, it is as follows:

local function validateColor(source)
  --# parse number inputs
  if tonumber(source) then
    local shifted = math.floor(math.log(tonumber(source))/math.log(2))
    if shifted >= 0 and shifted <= 15 then
      return col
    end
    return false, "colour out of range"
  --# parse string inputs
  elseif type(source) == "string" then
    source =  source:lower()
                    :gsub("%s*", "")
                    :gsub("colou?rs?%.?", "")
                    :gsub("lightb(.+)", "lightB%1")
                    :gsub("lightg(.+)", "lightG%1")
    source = colors[source] or colours[source]
    return source, (not source and "invalid string input")
  end
  --# reject other inputs
  return false, "expected number/string, got "..type(source)
end
the above function makes sure it is a valid colour, and is only one colour. it supports a range of inputs which can be seen here. to use it do the following


local col, err = validateColor( yourInput )
if not col then --# it wasn't valid input
  print( err ) --# why it wasn't valid
end
ByteMe #3
Posted 20 December 2014 - 02:47 AM
I was about to press post after writing code I sourced of… ccConfig then I saw theoriginalbit was typing and remembered he was probably typing the same thing as me. (being the creator of ccConfig)
ebernerd #4
Posted 20 December 2014 - 02:53 AM
Thanks you guys!