-
Notifications
You must be signed in to change notification settings - Fork 116
[Tutorial] Hooks
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...
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 an user uses (By default 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)
The result would be similar to:
It's really simple, all you have to know is hook name and some unique name of your choice (it's 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.
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")
You can even create a hook (or call any standard one) yourself! All you have to do is executing:
hook.run("name", ...)
"..." are your arguments passed to hooked functions.
Example:
hook.add("myveryownhook", "some_unique_name", function(text)
print(text)
end)
hook.run("myveryownhook", "hello")
Code above will simply print hello
to chat.
When you add another hook under the same uniqueid it will override first one, meaning only second one will execute.
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 useful, more on that in rendering tutorial.
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.
If you want to check your understanding of hooks you can do this simple task:
Create a script that prints a message on your chat when user player enters a vehicle, but only first 5 times, after that remove hook. (Solution)