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.
If one script needs to explicitly call a function in another script, you can use Lua modules. Modules are scripts that return some value and allow other scripts to access that value.
In answer to the question: you need to create a function in one script into the global table - _G, by adding _G. MyFunction = function(parameters) end. In another script, you need to access it inside the _G table - _G. MyFunction().
Lua offers a higher-level function to load and run libraries, called require . Roughly, require does the same job as dofile , but with two important differences. First, require searches for the file in a path; second, require controls whether a file has already been run to avoid duplicating the work.
Being an extension language, Lua has no notion of a "main" program: it only works embedded in a host client, called the embedding program or simply the host. This host program can invoke functions to execute a piece of Lua code, can write and read Lua variables, and can register C functions to be called by Lua code.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With