dansanderson / picotool

Tools and Python libraries for manipulating Pico-8 game files. http://www.lexaloffle.com/pico-8.php
MIT License
367 stars 46 forks source link

require() argument to generate global aliases for "imported" symbols #44

Open dansanderson opened 6 years ago

dansanderson commented 6 years ago

The Lua module idiom recommended with require() has several kinds of token overhead that impact Pico-8 developers: a one-time cost of +49, a per-library cost of +9, and possibly +1 per exported symbol to arrange a library in table form. Another potential costly area of overhead is dereferencing the exported symbols from the table, with a cost of about +2 per reference.

This last one could be mitigated by aliasing the exported symbol into a global, effectively "importing" the symbol into the global namespace with a cost of +4 tokens per import:

MyLib = require('mylib.lua')
someMethod = MyLib.someMethod

someMethod()
someMethod()
someMethod()

Today, devs can set up these aliases automatically. I'm wondering if it might be handy for this to be a build-time-only argument to require() to generate these, a sort of "import" statement. The following would produce the same code as above:

MyLib = require('mylib.lua', import={'someMethod'})

someMethod()
someMethod()
someMethod()

This is only a modest convenience if the imports have to be listed. A "import all" feature would be useful, but unfortunately it would be impractical to thoroughly determine the list of symbols to alias with just static code analysis. (Maybe we could use a Lua-based helper to evaluate the module code and iterate over the table it returns, though that would require installing Lua. Or implementing a Lua interpreter. :) )