User Tools

Site Tools


script:walkthrough:functions

This is an old revision of the document!


Records 
 Scopes

Functions

A function is defined in the current scope using a def statement. def is a compound statement, so it must be either a single-line compound or end must be used in the end.

def func1(): pass

def func2()
end

The return statement is used to return a value from a function.

def func3(): return 'World'
print 'Hello', func3()

Arguments

Functions can be defined with a list of untyped arguments.

def func5(a, b, c)

Default values can be included.

def func5(a, b='default', c=100)

When calling a function, all arguments must have values. Argument names can always be included in the function call, regardless of whether they were defined with default values or not. When using names, the order can also be changed.

func5(c=5, a=100, b='OOO')

Records as arguments/return value

Records are passed by reference both in arguments and in the return value. This means that if a record is created as a local variable, it will be deleted even though it is returned.

def func4()
    record a       # 'a' owns the record
    a.value = "func4"
    return a       # non-owned reference returned
end
print func4()      # throws NullError!

In this case, one could instead use the Record() function to return a copy of the record to the caller.

return Record(a)

When passing a record as argument, the function gets a non-owned reference.

record myrec
myrec.val = 'Original'
print myrec.val
def modify(r)
    r.val = 'Changed'
end
modify(myrec)
print myrec.val

Output:

Original
Changed

Note that records are always passed by reference, even when specifically passing in an owned reference as argument. In the example below, the created record exists only for the duration of the function call. The function's local variable rec is initialized with a non-owned reference to the record. This non-owned reference is returned, and thus an invalid reference will be assigned to a. Trying to access a after this would return in a NullError exception.

def do_init(rec)
    rec.val = 'inited'
    return rec
end
a = do_init(Record())  # returns null ref!
It is advisable to not use Record() in arguments. Only use it to assign an owned reference to a local variable.
  • Passing arguments.
  • Passing record as argument.
  • Default values to function arguments.
  • Defining function in a record.
  • Defining a function within a function.
  • Accessing function's locals within a sub function.
  • Reference to function.
  • Callback function as argument.
  • Returning a local function from a function.
Records 
 Scopes
script/walkthrough/functions.1574538260.txt.gz · Last modified: 2019-11-23 21:44 by skyjake