[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: v <v19930312@...>
- Date: Mon, 10 Jul 2023 14:17:26 +0300
On Mon, 2023-07-10 at 09:33 +0200, bil til wrote:
>
> > var = io.read()
> > if (string.match(var, "%a+_%a+")) then -- In this example, _ will
> > be normal
> > print("Valid variable name !")
> > else
> > print("Invalid variable name")
> > end
>
Thischecks for presence of a sequence of alphabetical characters
followed by an underscore followed by more alphabetical characters. So
"myvar" won't pass while "my_var" and "*/*my_var+++--" will. Not sure
that's what you want.
>
> ... also probably most fast like this, and also this for sure will be
> necessary/useful to check (I then want to use this further in my Lua
> user program as _G[var], as described in Roberto's PiL Book Chapter
> 22 ("Global VAriables with Dynamic Names")).
>
> (if this is NOT necessary / useful, please correct me...).
>
Variable names are restricted only when it comes to accessing them via
usual syntax. _G is a table like any other, so any key (even non-string
one!) can be used in it with the sole consequence being your inability
to access such a value without explicitly indexing _G.
But IMO if you're going after variables with dynamic names you probably
want to have them in a separate table from _G to prevent trouble from
potential collisions. Just my 5c.
--
v <v19930312@gmail.com>