When I specify env in playdate.file.run(), the correct table does not seem to be referenced if I import from the run lua source.
-- main.lua
function test_main()
print('test main')
end
local pseudoEnv = {}
local mt = {}
mt.__index = _G
setmetatable(pseudoEnv, mt)
-- ng
playdate.file.run('test', pseudoEnv)
-- ok
--playdate.file.run('test')
function playdate.update()
end
-- test.lua
import 'test2'
test_main()
-- test2.lua
test_main()
When I do the above, I get the following error.
test2.lua:1: global 'test_main' is not callable (a nil value)
By the way, if you do not specify env in playdate.file.run(), it works fine.
Okay, I think I've figured out what's going on. Thanks so much for putting together the very clear demo! It looks like our code that sets the environment for imports inside loaded code never worked right, was trying to set a table from the stack but inside the import call the stack has been reset. It took a while but I've got a fix now: I changed the import function from a plain c function to a closure so that I can set an upvalue on it, and I'm using that to set the environment inside the import. One possible gotcha: Since that's set when the first file gets loaded, if you set the _ENV variable in that code it doesn't get set in the import environment. That seems like a very obscure case, hopefully won't trip anyone up.
It'll be a while before that fix makes it to a release, though. In the meantime, you could use playdate.file.run() instead of import so that you can set the _ENV var in the run() call. Or another workaround is you could make pseudoEnv global and do
if pseudoEnv ~= nil then _ENV = pseudoEnv end
at the top of any imported files that should use it.