dofile ("file.lua") or loadfile ("file.lua") - do not seem to be used widely?

Hi

I came across the dofile () and loadfile() options and thought they were pretty cool, in many ways they seems similar to using ?require? etc.

Is there something wrong with dofile() or loadfile() with Vera, as I?m just curious why they do not seem to be used widely on this forum as a way to load a chunk of code ?

Well, it could be that the lua files are compressed automatically by Vera. So if you attempt to use dofile() or loadfile() at runtime you’d have to deal with that.

dofile() is a one-off load-and-execute action, and, as such, it really doesn’t have the functionality that’s required of a ‘real-time’ system which essentially executes in a continuous loop. You could use it as part of initialisation code, but see next sentence for some limitations.

loadfile() at least enables you to call it as a separate function multiple times, but both it and dofile() execute in the context of the global environment and therefore miss out to some extent on one of Lua’s key strengths which is lexical scoping, which allows functions to access the variables and functions of any nested enclosing contexts.

require() is similar to loadfile, but parts of a much more sophisticated construct which checks to see whether the file has already been loaded, and also searches a predefined directory tree for the module, so you don’t actually have to know exactly where it’s located. It is therefore THE mechanism for loading both system and user library modules.

In Vera, the use of require() is somewhat stunted by the modifications MiOS has made to cope with compressed and encrypted functions, so it’s not able to cope wit the more ‘modern’ Lua pattern for defining modules (without the module() statement.)

In openLuup, I use loadfile() extensively as part of the process of building plugins from device implementation files. In that case, it’s exactly what’s needed.

Being such a compact and elegant language, Lua does not waste resources on replicating functionality, so each of the methods has their own place. Whilst you can write dofile() in terms of loadfile(), it’s certainly more compact to not have to do that. On the other hand, you would really struggle to duplicate require() using loadfile().

Horses for courses.

Thanks @akbooer

That helps me in my never ending journey to learn Lua - in my sadly very limited spare time :frowning:

Its always interesting to understand the options of how to do things - each with their own subtle differences