ComputerCraft

ComputerCraft

21M Downloads

Global Functions?

bmccalmon opened this issue ยท 4 comments

commented

I cannot call a function from another lua file. Is the default changed to local?

commented

So do you suggest I write my OS in one main file? I always treated the separate lua files as separate classes. Now that I can't set global variables or functions I think otherwise.

commented

You've got three options:

  • Don't use globals unless you absolutely have to. There are generally much nicer ways of sharing code or splitting it up, such as require.
  • Load code explicitly into the global environment, using something like loadfile.
  • Explicitly use _G (_G.my_variable = xyz (or function _G.my_function() end) in order to change global environment.
commented

To clarify, it's usually best to define your code as files which return anything you want to share - e.g. a table of functions. Then, you can use local functions = require("file") to load them from a different file.

commented

I suspect you were running files using shell.run, which now loads each file within it's own environment table. This means that globals set by one program to not interfere with programs set by another.

If you need to load things from another file, I'd recommend using require or dofile/loadfile instead. One should try to avoid setting globals wherever possible.