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

Multiple files: attempt to call nil

Started by LucasShadow, 13 July 2013 - 12:55 AM
LucasShadow #1
Posted 13 July 2013 - 02:55 AM
I am trying to split up a rather large program into multiple files. A sample program is shown below:


--File1
local M = {}
M.variable = 5
return M

--File2
obj = require('File1') <- Error found here
println(obj.variable)

Is this not the way to include other files with the file you are working on?
ElvishJerricco #2
Posted 13 July 2013 - 03:29 AM
The module system of Lua is not included in CC. You'll have to do something like this:


--File1
local M = {}
M.variable = 5
return M

--File2
local f, err = loadfile("full/path/to/File2") -- load the file as a Lua function
assert(f, err) -- error out if there is something wrong with the file
local obj = f()
print(obj.variable)

And if you want to be a good citizen, you'd set the environment on f so that any globals it declares are in the environment you created instead of _G.
LucasShadow #3
Posted 13 July 2013 - 05:43 PM
Ah, perfect. Thanks a lot.