terralang / terra

Terra is a low-level system programming language that is embedded in and meta-programmed by the Lua programming language.
terralang.org
Other
2.72k stars 201 forks source link

Terra doesn't inject requirable library #382

Open aiverson opened 5 years ago

aiverson commented 5 years ago

Since terra builds a terra.so now which is designed to be required from luajit code, it should inject a package.loaded["terra"] so that code written in lua can safely local terralib = require 'terra' and have it work whether it is running from the terra executable or loading terra from a shared library in a different lua interpreter.

aiverson commented 5 years ago

I'll do this myself, but I'm putting it here for communication and reminder.

elliottslaughter commented 5 years ago

Isn't that what terra_init is for? Should we expose this in some way so it's easier to use?

aiverson commented 5 years ago

Currently, terra exposes luaopen_terra which gets called when the terra dynamic library is loaded by lua. When running in a luajit instance that isn't owned by terra, the call require 'terra' will search for a terra library in the cpath and the link it and invoke luaopen_terra. Currently, this call just assigns to the terra globals but doesn't return the library, which is nonidiomatic, but is at least consistent.

However, because the Terra executable doesn't inject itself into the package.loaded table, the require 'terra' call will fail when run from anything loaded in the Terra executable, but will succeed in things run from luajit with terra as a dynamic library.

The fix is simple. In main.cpp:main, I'll just add a section that does package.loaded['terra'] = true during the LuaState initialization. Then a lua file can have require 'terra' succeed consistently whether it is being invoked from terra or from luajit with terra as a library.

elliottslaughter commented 5 years ago

That seems reasonable, thanks.