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.
No, you don’t have to create a module. If you just create
foo.lualike this:And then in your script,
require 'foo', you will be able to access thedoublefunction 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 — allmodule 'name'does is create a new table and reset the current environment to that table.So, you can just do:
In
GameObjectUtils.lua, and if yourequire 'GameObjectUtils', thenSlimecan just useslimefunc. Or, if you want it to be namespaced: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.)