This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Ulthean's profile picture

[LUA] Import a function from another file

Started by Ulthean, 07 January 2013 - 07:32 AM
Ulthean #1
Posted 07 January 2013 - 08:32 AM
Hello,

is there a way to import a function or all the functions from another lua file? Basically I want to have two files:
  • tools.lua containing a function readConfig(filename)
  • main.lua using the readConfig function
PixelToast #2
Posted 07 January 2013 - 08:34 AM
you can use os.loadAPI(filename)
wont work so well with files that end with .lua though
Ulthean #3
Posted 07 January 2013 - 08:40 AM
No problem, this is exactly what I needed, sorry for being silly :)/>
NeverCast #4
Posted 07 January 2013 - 02:38 PM
alternatively you can use dofile, loadfile or loadstring.

Load string is always fun, it creates a function with the content you specify. So if I wanted to create a function by source I could do.

loadstring( "function newFunction() return 10 end")()

LoadString takes the source from the string, and puts it in to a function that is returned to you, I then call the returned function with the () at the end. so now newFunction has been declared.
If you type lua in to a CC Computer or Turtle and do


loadstring( "function newFunction() return 10 end")()
newFunction()

The result 10 will be printed.

If you're feeling brave, look through these http://pgl.yoyo.org/luai/i/loadstring