Paste: lua module in clay

Author: ks
Mode: text
Date: Wed, 2 Mar 2011 03:53:09
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)
        lua.genericError(x, "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, "
            mylib.sayHello()
            sum, average = mylib.sumAndAverage(1, 2, 3, 4, 5, 6)
            print('sum = ' .. sum)
            print('average = ' .. average)
        ");
    }
    catch (e:lua.Error) {
        println("error: ", e.msg);
    }
}

New Annotation

Summary:
Author:
Mode:
Body: