Making an API (tutorial)

From ComputerCraft Wiki
Jump to: navigation, search

Making an API

An API is a program that is not directly executed, but is a collection of variables that can be accessed from any program on that computer.

To make an API, you must create a new file. I will call it myapi. Fill it with variable declarations as normal, but without the local keyword:

-- My awesome new API

myvar = "Hello World!"

function myCoolNewFunction()
    print(myvar)
end

Now try it out. Save and exit the file, then open the lua program on your ingame computer. Then type:

os.loadAPI("myapi") -- replace myapi with the name of your API.
myapi.myCoolNewFunction()

If you have written the program correctly, you will see Hello World! printed to your screen. Now try:

print(myapi.myvar)

You should also see Hello World! printed to your screen. Congratulations, this is your first API!


Locals vs Globals

OK, lets go back to our API.

-- My awesome new API

myvar = "Hello World!"

function myCoolNewFunction()
    print(myvar)
end

If we change our declaration for myvar to local, like this:

-- My awesome new API

local myvar = "Hello World!"

function myCoolNewFunction()
    print(myvar)
end

we should get the same result if we call myCoolNewFunction(). REMEMBER: you will need to load the API again to apply your changes!

But what happens if you try print(myapi.myvar)?


It prints nothing. This is because we changed the declaration for myvar to local! This is useful if you want to have a variable visible to only your API. It will also work with functions, like this.

-- My awesome new API

local myvar = "Hello World!"

local function myCoolNewFunction()
    print(myvar)
end

Now if you try to call myCoolNewFunction(), you will get an attempt to call nil error.