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

Run only a certain function from a program

Started by EveryOS, 04 April 2016 - 06:39 PM
EveryOS #1
Posted 04 April 2016 - 08:39 PM
I need to run only a specific function from a program. Is this possible?
KingofGamesYami #2
Posted 04 April 2016 - 09:59 PM
This is what APIs are for.
Bomb Bloke #3
Posted 05 April 2016 - 12:54 AM
I've gotten into the habit of writing certain scripts such that they can either be executed normally or loaded as APIs. This is done by checking for the "shell" table, which is unavailable when your file is loaded through os.loadAPI().

For example, check around lines 366 and 531 of package.
EveryOS #4
Posted 05 April 2016 - 12:51 PM
The reason I need to do this is to garauntee I only run what's needed- I don't know what I may find outside of that function.
KingofGamesYami #5
Posted 05 April 2016 - 01:37 PM
What if the function references variables that were defined outside of it? If you don't run that code, the function won't work properly.
Lupus590 #6
Posted 05 April 2016 - 02:07 PM
If it's just one function then why not just copy it into your program?
Bomb Bloke #7
Posted 05 April 2016 - 02:15 PM
Presumably you're trying to say that you don't want to use APIs. What you're not saying is why, which is more than a bit relevant to figuring out the best way to do… whatever it is you're trying to do.
EveryOS #8
Posted 05 April 2016 - 02:50 PM
What you're not saying is why.
It's for a emulator of another programming language, which searches out a specific function and only runs that one function.
Edited on 05 April 2016 - 12:50 PM
Bomb Bloke #9
Posted 06 April 2016 - 01:07 AM
Ok, so why can't you just load the file as an API, check whether the API table has the function you want, and execute it if so?

The functions defined in a Lua script don't become functions until the code is executed. os.loadAPI() works by executing the script file in its own little sandbox and saving any declared globals into a table. You can then execute those functions via that table, if you choose.

If you really don't want to do it that way, then your alternative option is to load the whole file as a string, then manually parse through that to find the function declaration you want. You'll need to keep track of all blocks (if/while/do/whatever) that the function opens and closes in order to pinpoint its exact end, so that you can create a new string containing just the declaration of that one function, which you can then finally manually compile into something executable via loadstring() / dostring().
EveryOS #10
Posted 06 April 2016 - 01:46 AM
I guess I'll just have to do the second way.