Skip to content
Damianu edited this page Aug 19, 2017 · 11 revisions

Hooks? I didnt see anything like that in Expression 2..

Unlike E2 in starfall code outside hooks is executed only once. Example:

--@name Hello World
--@server

print("Hello world!")

"Hello world" will be printed only once unless we reload the chip.

Unlike E2 we dont execute whole code each tick or when input changes. That's because...

What are hooks?

Hooks are events, it means that starfall will execute function you provided with some arguments depending on which hook you choosen.

Let's say we want to print a message when user uses(By defualt by pressing E on it) starfall chip.

--@name DTut: Hooks
--@server

hook.add("PlayerNoClip","some_unique_name",function(user, state)
    if state then
        print("Oh wee! "..user:getName().." is using noclip!")
    else
        print(user:getName().." isn't using noclip anymore")
    end
end)

Result would be similar to:

So how do I use them exacly?

It's really simple, all you have to know is hook name and some unique name of your choice(its used later if you want to remove said hook).

You can get hook name in SF Helper:

Now when you know the name of the hook, all you have to do is executing this function: hook.add(hook_name,unique_id, func)

func can be normal or anonymous function (more)

Example using non-anonymous function:

--@name DTut: Hooks
--@server
function announceNoclip(user, state)
    if state then
        print("Oh wee! "..user:getName().." is using noclip!")
    else
        print(user:getName().." isn't using noclip anymore")
    end
end

hook.add("PlayerNoClip","some_unique_name", announceNoclip)

It's all matter of your preferences and/or needs.

What if I dont want to execute hook anymore?

That's what unique id was for! You can remove hook by passing hook name and unique id to hook.remove function.

hook.remove("PlayerNoClip","some_unique_name")

#Some common questions:

What happens when I add hook twice using same unique id?

When you add another hook under same uniqueid it will override first one, meaning only second one will execute.

Can I execute hook only once?

Yes, you have to remove it inside it's own function, it would look like:

hook.add("renderoffscreen","some_unique_name",function()
    print("Oh wee, I am in render frame!")
    hook.remove("renderoffscreen","some_unique_name")
end)

It's quite usefull, more on that in rendering tutorial.

Are unique names colliding between various hooks?

No, each hook has its own set of unique names, it means that you can have "some_name" in both "render" and "tick" hooks and they wont override.

Clone this wiki locally