Lua - How to use functions from another script

lua

Solution

No, you don't have to create a module. If you just create `foo.lua` like this:

function double(n)
  return n * 2
end

And then in your script, `require 'foo'`, you will be able to access the `double` function just like it was defined in the same script. Those functions can't get at your locals, but they are created in the same environment -- all `module 'name'` does is create a new table and reset the current environment to that table.

So, you can just do:

function slimefunc(...) stuff() end

In `GameObjectUtils.lua`, and if you `require 'GameObjectUtils'`, then `Slime` can just use `slimefunc`. Or, if you want it to be namespaced:

utils = {}

function utils.slimefunc(...) stuff() end

And it will be accessible as `utils.slimefunc`. (If you do that, you'll have to be really careful about not letting your names leak - make judicious use of locals.)

Problem

I'm wondering how to use functions from another script in Lua. For example, say `GameObjectUtilities` holds functions that many `GameObject` scripts will use. The `Slime` (a `GameObject`) script wants to use a function in `GameObjectUtilities`. I'm having trouble getting this to work. I've looked here, but I still don't really fully understand. Do I need to create a module or a table to hold the functions in `GameObjectUtilities` for the functions in it to be used in other scripts? If so, what is the best way to go about this? It's very odd. It actually does work when I just do it the normal way. The problem is that when I run my app and it tries to use the script it doesn't work. I don't get it.

Original source