4

I'm making a fully working add and subtract program as a nice little easy project. One thing I would love to know is if there is a way to restrict input to certain characters (such as 1 and 0 for the binary inputs and A and B for the add or subtract inputs). I could always replace all characters that aren't these with empty strings to get rid of them, but doing something like this is quite tedious.

William Barbosa
  • 4,936
  • 2
  • 19
  • 37
Wojciech72
  • 41
  • 1
  • 3
    Doing that isn't tedious it is one line (`inline = inline:gsub("[^01]","")` and add `:sub(1,1)` to the end of that if you only want the first valid number) and if you don't want to strip the input then you can check it and reject it instead. – Etan Reisner Dec 05 '14 at 17:11
  • 1
    Could follow the advice of this thread: http://stackoverflow.com/questions/5689566/keypress-event-in-lua and once you have a "getch" implementation, then you could use it to only allow input of the characters you want – Chris Dec 06 '14 at 01:02

1 Answers1

1

Here is some simple code to filter out the specified characters from a user's input:

local filter = "10abAB"
local input = io.read()
input = input:gsub("[^" .. filter .. "]", "")

The filter variable is just set to whatever characters you want to be allowed in the user's input. As an example, if you want to allow c, add c: local filter = "10abcABC".

Although I assume that you get input from io.read(), it is possible that you get it from somewhere else, so you can just replace io.read() with whatever you need there.

The third line of code in my example is what actually filters out the text. It uses string:gsub to do this, meaning that it could also be written like this:

input = string.gsub(input, "[^" .. filter .. "]", "").

The benefit of writing it like this is that it's clear that input is meant to be a string.

The gsub pattern is [^10abAB], which means that any characters that aren't part of that pattern will be filtered out, due to the ^ before them and the replacement pattern, which is the empty string that is the last argument in the method call.

Bonus super-short one-liner that you probably shouldn't use:

local input = io.read():gsub("[^10abAB]", "")
MarkSill
  • 73
  • 1
  • 8