Paste: lua+clay error handling

Author: ks
Mode: text
Date: Wed, 2 Mar 2011 04:15:20
Plain Text |
import lua;

sayHello(x:lua.State) {
    println("Hello from Clay!");
    return 0;
}

sumAndAverage(x:lua.State) {
    var n = lua.getTop(x);
    assert(n >= 0);
    if (n == 0)
        throw lua.Error("atleast one argument expected in 'sumAndAverage'");
    var sum = 0.0;
    for (i in range(1,n+1))
        sum += lua.checkNumber(x, i);
    lua.pushNumber(x, sum);
    lua.pushNumber(x, sum/n);
    return 2;
}

main() {
    var x = lua.State();
    lua.openLibs(x);
    lua.registerModule(x,
        "mylib",
        ("sayHello", sayHello),
        ("sumAndAverage", sumAndAverage),
    );
    try {
        lua.doString(x, "
            require 'mylib'
            mylib.sayHello()
            sum, average = mylib.sumAndAverage()
            print('sum = ' .. sum)
            print('average = ' .. average)
        ");
    }
    catch (e:lua.Error) {
        println("error: ", e.msg);
    }
}

/*
OUTPUT:
Hello from Clay!
error: atleast one argument expected in 'sumAndAverage'
*/

New Annotation

Summary:
Author:
Mode:
Body: