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

[kinda solved] Overriding an API function

Started by PonyKuu, 13 March 2013 - 08:34 PM
PonyKuu #1
Posted 13 March 2013 - 09:34 PM
Let's say, I have an API "apiA" and a global function A() in it. Some API functions use that function.

I want to write a program which uses the API but I want to replace the apiA.A() function with some other function B()
I try to do this:

apiA.A = B
And that doesn't work. Why?
immibis #2
Posted 13 March 2013 - 09:39 PM
Post your code if you're not getting it to work! We can't tell you what's wrong if we can't see your code.
PonyKuu #3
Posted 13 March 2013 - 09:47 PM
Oh… Okay.

Here is the API code:
http://pastebin.com/2SyQ3vD8
And here is the main program:
http://pastebin.com/zy9921dH

Put the turtle down. Give it an Ender Chest with some fuel, and run this program. What it SHOULD do - is use a chest to refuel itself, because I overrided the refuel function. But instead it's just using the refuel function from API
immibis #4
Posted 13 March 2013 - 09:55 PM
I think APIs always see their own functions, even though other programs will see the overridden ones.
PonyKuu #5
Posted 13 March 2013 - 10:00 PM
Is there any way to deal with it? I hate to rewrite the API just for one program… I will rewrite the program, because of some other serious issues, but that might be not the only case…
JokerRH #6
Posted 13 March 2013 - 10:08 PM
To understand why you'll have to understand how loadAPI() works.
To load an api it uses loadfile to load the code. Then it sets the function enviroment for your api wich will ensure that it doesn't use the global enviroment (That would be bad, you could for example only have one xy() function because they would overwrite each other).
As the last step it will loop through every index in the function enviroment and copy it into it's own table in the global enviroment
_G["yourAPIName"] = {"functions"}
That is the table you refer to if you say yourAPIName.functions.
But unfortiounatly if you manipulate the global index it won't change the function enviroment.
You can refer to it by typing getfenv() and setfenv(), but I think you can't do that from outside your api.

Edit: You don't have access to the lua function of your api, so you can't set it outside of your api.
if you say setfenv(1, yourNewTable) it will change the function enviroment of the current function, that is your api.
PonyKuu #7
Posted 13 March 2013 - 10:14 PM
Oh, thank you for the explanation!