alliedmodders / sourcepawn

A small, statically typed scripting language.
Other
362 stars 62 forks source link

Function Literals proposal #652

Closed assyrianic closed 3 years ago

assyrianic commented 3 years ago

I'd like to make a proposal for there to be function literals, at least to make it easier to create timers.

Here's something to what I have in mind: Source Code:

CreateTimer(1.0, function Action(Handle hTimer) {
    return Plugin_Continue;
}, _, TIMER_REPEAT|TIMER_FLAG_NO_MAPCHANGE);

"Generated" Code:

CreateTimer(1.0, FileNameFunction1, _, TIMER_REPEAT|TIMER_FLAG_NO_MAPCHANGE);

public Action FileNameFunction1(Handle hTimer)
{
    return Plugin_Continue;
}

Where each instance of a function literal is then named and that instance is replaced with the given name.

dvander commented 3 years ago

This syntax will come eventually, but not soon. We can't implement capturing yet, and without capturing, the value is pretty low.

assyrianic commented 3 years ago

but capturing would add too much unnecessary overhead. If someone really needs to capture variables, they can just pass it via parameter. Not to mention that global variables are "automatically" captured.

dvander commented 3 years ago

" If someone really needs to capture variables, they can just pass it via parameter."

How do you think capturing works? :)

assyrianic commented 3 years ago

I thought you meant the type of capturing where the data is stored in an environment. If the capturing can be done where it's just passed to the function as a parameter under the hood, I'd be a happy camper then.

dvander commented 3 years ago

It's exactly the same thing. The "environment" is lifted into CreateTimer right now because we don't have capturing. But ideally, it would be part of the language.

dvander commented 3 years ago

https://cs.alliedmods.net/sourcemod/source/core/TimerSys.cpp#311 https://cs.alliedmods.net/sourcemod/source/core/logic/smn_timers.cpp#206

We allocate an object to store the callback data, and then pass it in as an argument when it's time to make the call.

asherkin commented 3 years ago

Related: #181