lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Another alternative occurs to me: You could instead, if you wished, use newindex to track the items assigned by the script. Depending on how your stuff works this might have advantages: you wouldn't have to iterate because you'd get each assignment pushed to you. Doesn't work as well for table-valued variables without additional hackery (setting a metatable on user-created tables in that newindex callback) but it might be interesting.

/s/ Adam

On Mon, Jun 21, 2021, 11:08 AM Coda Highland <chighland@gmail.com> wrote:
You could use a metatable to solve that: if _ENV's index contains the global functions you want the code to be able to look up, then that example will work while not having those globals appear in the iteration order.

/s/ Adam

On Mon, Jun 21, 2021, 11:00 AM Andrew Yan <aky26@cornell.edu> wrote:
Sorry, I forgot to specify that I am interested in iterating over arbitrary options, i.e. I don't know which options will be present in `conf.lua`, while also letting users execute arbitrary code, e.g. print statements for diagnostics.
Example (suggested) `conf.lua`
```
print(1) -- 1
custom_option = 1 -- I can't anticipate this 
```
IIRC what you're suggesting would lead to a polluted namespace with `print`, etc., which is undesired.
Hence, the motivation for a final optional _expression_.

Thanks,
Andrew

On Sun, Jun 20, 2021 at 5:03 PM Sean Conner <sean@conman.org> wrote:
It was thus said that the Great Andrew Yan once stated:
> In Lua 5.3, this code is unparseable:
> ```
> function huh() 1 end
> ```
> Would it be possible in future versions of Lua to instead make it return
> `1` when called, i.e. to permit a final optional _expression_? AFAIK this
> wouldn't break anything since the above statement can't be parsed anyways.
>
> The motivation for this is lua configuration files.
> Example:
> `conf.lua`
> ```
> -- statements...
> {
> option1=1;
> option2=2;
> }
> ```

  You can get the same effect by removing the table constructor:

===conf.lua===

option1 = 1
option2 = 2

===

To read  in the file:

        local conf = {}
        local f,err = loadfile("conf.lua",'t',conf)
        if not f then error(err) end
        f()

        -- now you have conf.option1 and conf.option2

  I have used this method multiple times with no issues.  You can check out:

https://github.com/spc476/port70/blob/master/port70.lua#L46 (code)
https://github.com/spc476/port70/blob/master/sample-conf.lua (sample config file)

for an example.

  -spc