[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Fast Lua code checking, whether user entered a valid variable name?
- From: Francisco Olarte <folarte@...>
- Date: Mon, 10 Jul 2023 13:02:16 +0200
On Mon, 10 Jul 2023 at 08:31, bil til <biltil52@gmail.com> wrote:
> Sorry, for this quite basic question, but I do not find nice answers
> for this in Internet - although I think this is quite a common problem
> for a Lua user program:
>
> I would like the user to enter some variable name, or just some name
> which then I also want to use as name for a Lua global object.
>
> Is there any fast / standard method in my Lua user program to check,
> whether the user entered a string which is allowed as a "standard
> name" for a variable naming? (start by ascii char, containing only
> chars and numbers and '_')? (As I see, there are not such "C style
> character checking" functions in basic Lua, like "ischar / islower /
> isupper / isdigit...").
I'm not completely sure you do not mis some, but man 3.1 says:
Names (also called identifiers) in Lua can be any string of Latin
letters, Arabic-Indic digits, and underscores, not beginning with a
digit and not being a reserved word. Identifiers are used to name
variables, table fields, and labels.
Which you can check with a regexp....
"^[%a_][%w_]*$"
You can then check a table of reserved names, or you can also try to
be creative with load and let lua check it for you:
> function ok_var(v) return load("local "..v,nil,'t') and true end
> ok_var("___")
true
> ok_var("AND")
true
> ok_var("and")
nil
> ok_var("1and")
nil
> ok_var("hola")
true
> ok_var("hola.manola")
nil
( note this is after regex, so no attacks to load if I am correct, but
limiting to text just in case, also last one would have been filtered
by it )
I think you can combine all in a one lines ( use three or more
clarity, this is for easy cut & paste ):
> function ok_var(v) return string.match(v,"^[%a_][%w_]*$") and load("local "..v,nil,'t') and true end
> ok_var("a=do_something_evil()+3")
nil
Experts may correct something missing, but unless you need a really
complex one that should be enough for a user.
> Or is it wise / without problems, to allow the user also to use "more
> bizarre names" for naming variables dynamically in his Lua code, e. g.
> variable names containing spaces, or UTF characters or further things?
Well, globals are just entries in _ENV, but unless you are building
something really complex which needs them , I would limit myself to
normal ones, or just the ones passing the regexp even if it filters
some valid ones.
Francisco Olarte.