General function defintion - jpbubble/NIL-isn-t-Lua GitHub Wiki
Function definition in NIL is heavily based on how it's done in C, however taken it more into a Lua like syntax
void Hello()
print("Hello World")
end
Hello() // outputs: Hello World
Just like in C (and its dialects) 'void' is used to set up a function with that won't return a value. (Now even the prototype is heavily protected against this, so don't even try it, you'll only get errors or values being ignored).
Now can a void also take parameters, sure:
void Hello(string name)
print("Hello, "..name)
end
Hello("Jeroen") // outputs: Hello, Jeroen
Now the types given to parameters are checked run-time. Why run-time? Most of all because due to the fact that there are variant variables in Lua, and the fact that NIL variables can be manipulated by pure Lua code if you know how and there's nothing NIL can do about it.
If you think these checks slow down your script too much, you can just leave out the type name, and then the variable will automatically be a variant, and not be be checked, since it can contain what you want anyway, so how much sense does it make to check it?
void Hello(name)
print("Hello, "..name)
end
Hello("Jeroen") // outputs: Hello, Jeroen
Now to functions returning a value.
number Sum(number a, number b)
return a + b
end
print(Sum(3,5)) // output: 8
Notes:
- Values MUST be on the same line as the 'return' keyword, except in the ground scope or 'var' typed functions. This due to some checkups.
- When 'return' is called without a value, number functions will return 0, string function an empty string, and boolean function will return false.
- Now you can mess a bit with the values you give in the prototype of NIL. Future versions may have strict checking if the returned values are indeed what the function type is set for.
Multi-values return
Use "var" for that. Remember "var" means "variant" in NIL and not "variable" as in other languages.
var MultiReturn()
return 1,2,3,4
end
I do have a more sophisticated solution in mind, but I still need to figure out a clean way to implement that.