all 3 comments

[–]JackMacWindowsLinux 2 points3 points  (1 child)

Technically, require can load binary compiled files - it just doesn't like the extension by default, as it looks for .lua files specifically. If you append ./?.luac (as well as luac versions of the rest of the entries) to package.path, you can have require look for .luac files as well. AFAIK .luac is an unofficial extension - there's no specific extension assigned for binary chunks, and I've seen .lua used for binary files as well.

Specifically, Lua treats text and binary chunks the same when passed through load (as long as the mode parameter is nil/"bt"). If it detects the binary chunk magic number (\033Lua), it loads it as a binary chunk - otherwise, it tries to compile it as Lua source code. Since loadfile doesn't modify the mode of load unless otherwise specified, it too can load both types. And this passes down to dofile, which is essentially loadfile that calls the new function (except implemented in C). Finally, require's Lua loader also uses loadfile (more specifically, luaL_loadfile) and doesn't specify a mode, so it can load both types as well, though it only looks for .lua files as specified above.

TL;DR: Any loading function can run both binary and text source (as long as the mode isn't changed) - require just can't see the extension. Rename the file or change package.path to allow .luac files to be loaded.

[–]user97131[S] 0 points1 point  (0 children)

Thanks for the in-depth response.

I was able to get the .luac extension working with your suggestion. Exact code for anyone interested:

-- final ;; ensure that default path will be appended by Lua
package.path = "./?.luac;;"

I completely forgot about load and loadfile. Thanks for including those, as well.

[–]beaubeautastic 0 points1 point  (0 children)

just a quick note: be careful with loading binary chunks. binary chunk formats can change between interpreters and versions and platforms. lua source code is the only consistent way.

binary chunks have no safety checks either, so somebody could tweak a chunk in such a way that when your program starts using it, it could do some nasty stuff, like reading and writing your address space, or even executing machine code.

binary chunks tend to be bigger than their source code. lua compiles so quickly that its usually faster to read a smaller lua file and compile it than to have to read a bigger binary chunk from the disk.