开发者

Lua - How to use functions from another script

开发者 https://www.devze.com 2022-12-23 23:48 出处:网络
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 开发者_如何学

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 开发者_如何学Gowants 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.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.)


You haven't given us enough information. For example, you don't say if GameObjectUtilities is defined or what its value is. (I'm guessing it is set to true.)

I highly recommend that you buy the second edition of Roberto Ierusalimschy's superb book Programming in Lua, which explains the idiomatic use of require and module very simply and clearly. It is also an excellent book for anyone using Lua to help get the most out of the language and libraries. As luck would have it, there is a free sample chapter which at the moment covers exactly the topic you're looking for. But buy the book anyway; it is $25 well spent :-)

If you don't want to buy the book, you can read the free sample chapter, and you can also read about how to do things the "old" way, without module(...), because the entire previous edition is free online.

One possible short answer is that your "utilities" script should probably create a table and return it.

0

精彩评论

暂无评论...
验证码 换一张
取 消