Delegates or function pointers - jpbubble/NIL-isn-t-Lua GitHub Wiki

In Lua "function" is not only a keyword, but also a variable type. After all functions in Lua are nothing more but variables with a function pointer in them. This allows Lua to very flexibly (sometimes TOO flexibly) assign entire functions.

NIL should therefore also have some kind of support for this.

Please note that NIL does not handle the 'function' keyword the way Lua (and many other programming languages) does. In NIL it's only a file type.

function Hello()

That creates in NIL a function expecting a function pointer as returned value. In order to avoid this confusion I recommend the keyword "delegate" (which I "stole" from C#, I admit). This will just be replaced by 'function' before NIL translates, but it makes your code less eligible for confusion.

Assigning an existing function to a delegate

       void Hello()
          print("Hello World")
       end
       
       delegate Hi
       Hi = Hello
       Hi() // Outputs: Hello World
       
       Hi = void()
          print("Hi folks!")
       end
       Hi() // Outputs: Hi folks!

Basically both (most common ways) to do this are demonstrated above. And in the above I just used void types, but other types can also be done

delegate b
b = boolean()
    return true
end
print(b()) // 'true'
b = boolean()
    return false
end
print(b()) // 'false'