Importing from other files

I’m new to Sonic Pi and just starting to learn how things work, and I’m curious if it’s possible to import functions between files. For example, I thought it might be nice to define a function that takes an array of notes and times and plays each note in sequence and then waits each time; and since I’d like to use this fairly often, defining it again in each new file seems problematic. Is it possible for me to define it in a separate file, and just access it with Ruby’s import 'filename' syntax? I’ve tried just doing exactly that, but I’m not sure where Sonic Pi is running the main file from and thus where it’s expecting to find any additional files.

It’s not the end of the world to not be able to create reusable functions like this, but boy would it be nice.

Hi

2 Likes

Yep, the excellent and detailed post by @ethancrawford that @nlb has linked to is definitely well worth a read.

For the TLDR, you can use the fns eval_file , run_code and run_file to load external code. See their documentation in the lang tab of the help system for more information and examples. For a quick run down:

  • eval_file - Reads the full contents of the file with path and executes within the current thread like a function call.
  • run_code - Executes the code passed as a string in a new Run. This works as if the code was in a buffer and Run button was pressed.
  • run_file - Reads the full contents of the file with path and executes it in a new Run. This works as if the code in the file was in a buffer and Run button was pressed.

So it sounds like you probably just want to use run_file. Simply place all your calls to define in a file, save it, and drag the file over to Sonic Pi’s GUI to get the full path. Depending where you saved it on your filesystem you should be able to do something like:

run_file "~/path/to/sonic-pi-code.rb" 

All calls to define within your file will be saved in memory and the newly defined functions will be available until Sonic Pi is closed.

Hope that this helps

3 Likes

That is all super helpful, thank you!

1 Like