This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Jummit's profile picture

require in dofile()

Started by Jummit, 20 May 2018 - 10:37 AM
Jummit #1
Posted 20 May 2018 - 12:37 PM
To make it short; you cant use require in dofile:
dofile_test.lua:

dofile("require_useing_file.lua")
require_useing_file.lua:

require("things_i_want_to_require")

It works in normal lua just fine, but in CC it says require does not exist:
dofile_test.lua:1: attempt to call global 'require' (a nil value)

Is this a bug or why is it different from normal lua?
Edited on 20 May 2018 - 11:43 AM
Bomb Bloke #2
Posted 20 May 2018 - 12:52 PM
Sorry, what was the question? Are you asking for a workaround, or just looking for confirmation of a bug?
SquidDev #3
Posted 20 May 2018 - 12:54 PM
This is because require exists in the shell environment, but dofile loads (by default) in the global environment. You should instead pass in the current environment:

dofile("require_using_file.lua", _ENV)
Jummit #4
Posted 20 May 2018 - 12:59 PM
This is because require exists in the shell environment, but dofile loads (by default) in the global environment. You should instead pass in the current environment:

dofile("require_using_file.lua", _ENV)
I looked dofile() up, and I didn't saw you could specify the environment. Or did I look at the wrong lua version?
SquidDev #5
Posted 20 May 2018 - 01:03 PM
I looked dofile() up, and I didn't saw you could specify the environment. Or did I look at the wrong lua version?
Ahhh, it appears it isn't. Sorry, I always forget which functions allow it and which ones don't. You'll have to use loadfile with an environment argument and then invoke the resulting function.