Skip to content
Fasteroid edited this page Dec 25, 2024 · 10 revisions

This articles covers in-depth usage of lambdas, E2's function objects. If you haven't already seen basic usage in the syntax guide, you should do so before reading ahead.

Table of Contents

Introduction
  •  Closures

Examples
  •  Chat Command Look-Up Table

Introduction

The ability to create variables and store things in them is a vital component of many programming languages. The ability to create functions that take arguments is also rather paradigm. But what if you encounter a scenario where you yearn to do both in the same feature?

If you want to do any of the following...

  • Store a function in a variable
  • Pass a function to another function
  • Store a function on a table/entity
  • Store state inside a function

Lambdas are your solution!

Closures 📦

Closures are a feature in programming that allow functions to pass local values to new functions. Consider the following scenario, where we have a function that inputs a number, and returns a function that uses that input, without being passed the input directly.

function function makeIncrementer(X:number) {
    return function() {
        X += 1
        return X
    }
}

let IncrementFromOne = makeIncrementer(1)

print(IncrementFromOne()[number]) # prints 2
print(IncrementFromOne()[number]) # prints 3

So, what just happened here?

  • We called makeIncrementer with an argument of X = 1
  • makeIncrementer returned a function that needs the enclosing scope it was created in to work (it relies on X), hence the name "closure".
  • When we call IncrementFromOne, it increments the captured X and returns the result of that.
  • Each subsequent call, IncrementFromOne remembers what X was last time and returns increasing values accordingly!

You can depend on this behavior being isolated across two different calls of MakeIncrementer. Consider if we wanted two "incrementers" starting from different numbers. Conventional logic may think that one will overwrite the other, but you'll be pleasantly surprised to find that's not the case.

let IncrementFromZero = makeIncrementer(0)

print(IncrementFromZero()[number]) # Prints 1

let IncrementFromTen = makeIncrementer(10)

print(IncrementFromTen()[number]) # Prints 11
print(IncrementFromZero()[number]) # Prints 2
print(IncrementFromTen()[number]) # Prints 12

So, what we see here is that if we define a function, all the local variables (called upvalues) inside that function can be used as though they were its own, even if they aren't defined globally or in the function itself.

⚠️ BUT!

Be careful about what kinds of objects you try to capture with closures. If they aren't primitives (numbers or strings), you'll end up capturing a reference to the object rather than a true copy of it! This may lead to maddening "wtf is happening" kinds of behavior!

function function makeEvilIncrementer(T:table) {
    return function() {
        T["x", number] = ["x", number] + 1
        return T["x", number]
    }
}

let NumberInATable = table("x" = 1)

let EvilIncrementer1 = makeEvilIncrementer(NumberInATable)
let EvilIncrementer2 = makeEvilIncrementer(NumberInATable)

print(EvilIncrementer1()[number]) # Prints 2
print(EvilIncrementer2()[number]) # Prints 3 (????)

NumberInATable["x", number] = -1

print(EvilIncrementer2()[number]) # 0 (???????)

The closure's upvalue is only a reference to the original NumberInATable, and NOT a reference to a copy. For non-primitive values, making a copy is your responsibility!

So how do we fix the above behavior? Tables have a convenient method called :clone() that makes copying them easy:

function function makeLessEvilIncrementer(T:table) {
    T = T:clone()       # redefine the upvalue as a copy of itself
    return function() { # now carry on as usual
        T["x", number] = ["x", number] + 1
        return T["x", number]
    }
}

Careful using this method as a bandaid fix though—deep copying a table can get expensive fast!

Examples

Chat Command Look-up Table

🟢 Easy

If you're familiar with using look-up tables in E2, you can use function lambdas to create a chat command processor that you can easily extend and modify.

First, let's start with making our table to store functions, the command "keyword", and register the chat event. Inside the event, I'll put some code that checks if the Message starts with the keyword. Since it's only one character, I can cheat here by simply using array indexing to get the first character.

@strict
const Functions = table()
const Keyword = "/"

event chat(Player:entity, Message:string, _:number) {
    if(Message[1] == Keyword) {

    }
}

Now inside of the if statement, I'll put this code which will split the message after the keyword and also split apart the command from the rest of the arguments. Then, I'll have another if statement to check if the command exists inside the function table. If it does, I'll run it and pass the leftover array of arguments. I'll also add a warning if the user inputs a bad command, which isn't necessary but may be nice.

let Args = Message:sub(2):explode(" ") # Skip the first character ("/") and split the string into an array
let Command = Args:shiftString():lower() # Removes and returns the first element, and shifts everything down to compensate
if(Functions:exists(Command)) {
    Functions[Command, function](Args)
} else {
    print("Unknown command: " + Command)
}

If we were to run this now, we'll just keep getting the unknown command error because, of course, we haven't made any commands yet. So, let's see how simple it is to add new ones. I'll define some basic ones. At the top of our code, right after where we initialized Functions, we can add new functions just like so:

Functions["ping", function] = function(_:array) {
    print("Pong!")
}

Functions["hurt", function] = function(Args:array) {
    let Name = Args[1, string]
    let Player = findPlayerByName(Name)
    if(Player) {
        let Damage = Args[2, string]:toNumber()
        try {
            Player:takeDamage(Damage)
        } catch(_:string) {
            print("Damage is not allowed!")
        }
    } else {
        print(format("Couldn't find player %q", Name))
    }
}   

Important

The array argument is required even when it's not used. Your return type and function parameters need to be consistent for this to work, or you'll run into an error.

Now with all this together, we should be able to run our ping and hurt commands. You can add more commands just by adding a new function to the table.

Full code
@strict
const Functions = table()
const Keyword = "/"

Functions["ping"] = function(_:array) {
    print("Pong!")
}

Functions["hurt"] = function(Args:array) {
    let Name = Args[1, string]
    let Player = findPlayerByName(Name)
    if(Player) {
        let Damage = Args[2, string]:toNumber()
        try {
            print("Trying to hurt")
            Player:takeDamage(Damage)
        } catch(_:string) {
            print("Damage is not allowed!")
        }
    } else {
        print(format("Couldn't find player %q", Name))
    }
}  

event chat(Player:entity, Message:string, _:number) {
    if(Message[1] == Keyword) {
        let Args = Message:sub(2):explode(" ") # Skip the first character ("/") and split the string into an array
        let Command = Args:shiftString():lower() # Removes and returns the first element, and shifts everything down to compensate
        if(Functions:exists(Command)) {
            print("Calling " + Command)
            Functions[Command, function](Args)
        } else {
            print("Unknown command: " + Command)
        }
    }
}

Expression 2 ⚙️

Getting Started 🕊

Guides (In learning order) 🎓

Tools 🛠️

Click To Expand

Advanced

Beacon 💡

Control 🎛️

Data 💿

Detection 👀

Display 💻

Render 🖌

I/O 🔌

Physics 🚀

Utilities 🛠️

RFID 💳

Wireless 🛜

Gates 🚥

Click To Expand

TBD

Extras 🔭

Clone this wiki locally